当前位置:   article > 正文

Springboot 集成 Es 的相关操作_springboot集成es

springboot集成es

注:文章皆为个人纪录,可用性请以最终结果为准,若有错还请大佬们指出,谢谢!

此文章重在spring boot中对6.3.2版本Es的各种操作,简单易学,暂不做基础概念梳理。

每个操作都已测试,请放心食用~~


步骤一:引入相关依赖

注:此处引入  elasticsearch-rest-high-level-client  的Java客户端,并且与Es相关所有工具的版本需保持一致

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <parent>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-parent</artifactId>
  8. <version>2.5.4</version>
  9. <relativePath/> <!-- lookup parent from repository -->
  10. </parent>
  11. <groupId>com.es</groupId>
  12. <artifactId>example</artifactId>
  13. <version>0.0.1-SNAPSHOT</version>
  14. <name>example</name>
  15. <description>Demo project for Elastic Search</description>
  16. <properties>
  17. <java.version>1.8</java.version>
  18. <elasticsearch.version>6.3.2</elasticsearch.version>
  19. <elasticsearch.clent.version>6.3.2</elasticsearch.clent.version>
  20. <fastjson.version>1.2.61</fastjson.version>
  21. <hutool.version>5.1.0</hutool.version>
  22. </properties>
  23. <dependencies>
  24. <dependency>
  25. <groupId>org.springframework.boot</groupId>
  26. <artifactId>spring-boot-starter-web</artifactId>
  27. </dependency>
  28. <dependency>
  29. <groupId>org.projectlombok</groupId>
  30. <artifactId>lombok</artifactId>
  31. <optional>true</optional>
  32. </dependency>
  33. <dependency>
  34. <groupId>org.springframework.boot</groupId>
  35. <artifactId>spring-boot-starter-test</artifactId>
  36. <scope>test</scope>
  37. </dependency>
  38. <dependency>
  39. <groupId>com.alibaba</groupId>
  40. <artifactId>fastjson</artifactId>
  41. <version>${fastjson.version}</version>
  42. </dependency>
  43. <dependency>
  44. <groupId>cn.hutool</groupId>
  45. <artifactId>hutool-all</artifactId>
  46. <version>${hutool.version}</version>
  47. </dependency>
  48. <!-- elasticsearch 依赖 -->
  49. <dependency>
  50. <groupId>org.elasticsearch</groupId>
  51. <artifactId>elasticsearch</artifactId>
  52. <version>${elasticsearch.version}</version>
  53. </dependency>
  54. <!-- elasticsearch Java操作客户端依赖 -->
  55. <dependency>
  56. <groupId>org.elasticsearch.client</groupId>
  57. <artifactId>elasticsearch-rest-high-level-client</artifactId>
  58. <version>${elasticsearch.clent.version}</version>
  59. </dependency>
  60. </dependencies>
  61. <build>
  62. <plugins>
  63. <plugin>
  64. <groupId>org.springframework.boot</groupId>
  65. <artifactId>spring-boot-maven-plugin</artifactId>
  66. <configuration>
  67. <excludes>
  68. <exclude>
  69. <groupId>org.projectlombok</groupId>
  70. <artifactId>lombok</artifactId>
  71. </exclude>
  72. </excludes>
  73. </configuration>
  74. </plugin>
  75. </plugins>
  76. </build>
  77. </project>

步骤二:yml 配置

配好Es相关信息

  1. server:
  2. port: 7777
  3. spring:
  4. application:
  5. name: EsStudyTest
  6. elasticsearch:
  7. schema: http # 协议
  8. address: 127.0.0.1:9200 # 连接地址(Es的 ip : port)
  9. connectTimeout: 5000 # 连接超时时间
  10. socketTimeout: 5000 # socket 连接超时时间
  11. connectionRequestTimeout: 5000 # 获取连接的超时时间
  12. maxConnectNum: 100 # 最大连接数
  13. maxConnectPerRoute: 100 # 最大路由连接数

步骤三:创建Es的配置类

获取 RestHighLevelClient  的入口

  1. package com.es.example.config;
  2. import org.apache.http.HttpHost;
  3. import org.elasticsearch.client.RestClient;
  4. import org.elasticsearch.client.RestClientBuilder;
  5. import org.elasticsearch.client.RestHighLevelClient;
  6. import org.springframework.beans.factory.annotation.Value;
  7. import org.springframework.context.annotation.Bean;
  8. import org.springframework.context.annotation.Configuration;
  9. import java.util.ArrayList;
  10. import java.util.List;
  11. /**
  12. * ElasticSearch 连接配置
  13. */
  14. @Configuration
  15. public class EsConfig {
  16. /** 协议 */
  17. @Value("${elasticsearch.schema}")
  18. private String schema;
  19. /** 集群地址,如果有多个则用英文都好相隔 */
  20. @Value("${elasticsearch.address}")
  21. private String address;
  22. /** 连接超时时间 */
  23. @Value("${elasticsearch.connectTimeout}")
  24. private int connectTimeout;
  25. /** socket 连接超时时间 */
  26. @Value("${elasticsearch.socketTimeout}")
  27. private int socketTimeout;
  28. /** 获取连接的超时时间 */
  29. @Value("${elasticsearch.connectionRequestTimeout}")
  30. private int connectionRequestTimeout;
  31. /** 最大连接数 */
  32. @Value("${elasticsearch.maxConnectNum}")
  33. private int maxConnectNum;
  34. /** 最大路由连接数 */
  35. @Value("${elasticsearch.maxConnectPerRoute}")
  36. private int maxConnectPerRoute;
  37. @Bean
  38. public RestHighLevelClient restHighLevelClient() {
  39. // 组装集群地址
  40. List<HttpHost> hostList = new ArrayList<>();
  41. String[] hostArray = address.split(",");
  42. for (String addr : hostArray) {
  43. String host = addr.split(":")[0];
  44. String port = addr.split(":")[1];
  45. hostList.add(new HttpHost(host, Integer.parseInt(port), schema));
  46. }
  47. HttpHost[] httpHost = hostList.toArray(new HttpHost[]{});
  48. // 构建连接对象
  49. RestClientBuilder builder = RestClient.builder(httpHost);
  50. // 异步连接延时配置
  51. builder.setRequestConfigCallback(requestConfigBuilder -> {
  52. requestConfigBuilder.setConnectTimeout(connectTimeout);
  53. requestConfigBuilder.setSocketTimeout(socketTimeout);
  54. requestConfigBuilder.setConnectionRequestTimeout(connectionRequestTimeout);
  55. return requestConfigBuilder;
  56. });
  57. // 异步连接数配置
  58. builder.setHttpClientConfigCallback(httpClientBuilder -> {
  59. httpClientBuilder.setMaxConnTotal(maxConnectNum);
  60. httpClientBuilder.setMaxConnPerRoute(maxConnectPerRoute);
  61. return httpClientBuilder;
  62. });
  63. return new RestHighLevelClient(builder);
  64. }
  65. }

步骤四:创建自定义注解

用于在实体上说明Es的索引与type

  1. package com.es.example.annotations;
  2. import java.lang.annotation.ElementType;
  3. import java.lang.annotation.Retention;
  4. import java.lang.annotation.RetentionPolicy;
  5. import java.lang.annotation.Target;
  6. /**
  7. * 自定义注解 声明Es的索引与type
  8. */
  9. @Target({ElementType.TYPE}) // 声明注解使用类型
  10. @Retention(RetentionPolicy.RUNTIME) // 声明注解生命周期为运行时
  11. public @interface EsDocument {
  12. /**
  13. * 索引
  14. */
  15. String index();
  16. /**
  17. * type
  18. */
  19. String type();
  20. }

步骤五:创建实体

  1. package com.es.example.entity;
  2. import com.es.example.annotations.EsDocument;
  3. import lombok.AllArgsConstructor;
  4. import lombok.Builder;
  5. import lombok.Data;
  6. import lombok.NoArgsConstructor;
  7. import org.springframework.format.annotation.DateTimeFormat;
  8. import java.util.Date;
  9. @Data
  10. @Builder
  11. @EsDocument(index = "test20210910", type = "doc") // 自定义注解,声明Es的索引与type
  12. @NoArgsConstructor
  13. @AllArgsConstructor
  14. public class UserInfo {
  15. /**
  16. * 姓名
  17. */
  18. private String name;
  19. /**
  20. * 年龄
  21. */
  22. private Integer age = 0;
  23. /**
  24. * 生日
  25. */
  26. @DateTimeFormat(pattern = "yyyy-MM-dd")
  27. private String birthday;
  28. /**
  29. * 工资
  30. */
  31. private Integer salary = 0;
  32. /**
  33. * 地址
  34. */
  35. private String address;
  36. /**
  37. * 备注
  38. */
  39. private String remark;
  40. /**
  41. * 测试数据
  42. */
  43. private String sayWords;
  44. /**
  45. * 创建时间
  46. */
  47. private Date createTime;
  48. }

步骤六:开始花式操作

说明

此步骤中的方法相对全面,且每一步都有注释,以及逻辑之间我都会做明显分隔,便于理解,

前部分做索引与文档的增删改操作,后半部分做查询操作,有明显分割提示,所有操作都在一个类中,成员变量共享,

但是我没有做每个方法的具体响应示例,重在"授人以渔"。

后面的一系列查询操作思路核心就五步:

第一步:创建查询条件;

第二步:创建查询源构建器,并将查询条件配置其中;

第三步:创建请求;

第四步:调用 RestHighLevelClient 客户端去获取请求响应体;

第五步:解析响应体

6.1 创建索引

  1. package com.es.example.service.impl;
  2. import cn.hutool.core.bean.BeanUtil;
  3. import cn.hutool.core.collection.CollectionUtil;
  4. import com.alibaba.fastjson.JSON;
  5. import com.es.example.annotations.EsDocument;
  6. import com.es.example.entity.UserInfo;
  7. import com.es.example.service.EsIndexOperationService;
  8. import lombok.extern.slf4j.Slf4j;
  9. import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
  10. import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
  11. import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
  12. import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse;
  13. import org.elasticsearch.action.bulk.BulkRequest;
  14. import org.elasticsearch.action.bulk.BulkResponse;
  15. import org.elasticsearch.action.delete.DeleteRequest;
  16. import org.elasticsearch.action.delete.DeleteResponse;
  17. import org.elasticsearch.action.get.GetRequest;
  18. import org.elasticsearch.action.get.GetResponse;
  19. import org.elasticsearch.action.index.IndexRequest;
  20. import org.elasticsearch.action.index.IndexResponse;
  21. import org.elasticsearch.action.search.SearchRequest;
  22. import org.elasticsearch.action.search.SearchResponse;
  23. import org.elasticsearch.action.update.UpdateRequest;
  24. import org.elasticsearch.action.update.UpdateResponse;
  25. import org.elasticsearch.client.RestHighLevelClient;
  26. import org.elasticsearch.common.settings.Settings;
  27. import org.elasticsearch.common.unit.Fuzziness;
  28. import org.elasticsearch.common.xcontent.XContentBuilder;
  29. import org.elasticsearch.common.xcontent.XContentFactory;
  30. import org.elasticsearch.common.xcontent.XContentType;
  31. import org.elasticsearch.index.query.BoolQueryBuilder;
  32. import org.elasticsearch.index.query.MatchAllQueryBuilder;
  33. import org.elasticsearch.index.query.QueryBuilders;
  34. import org.elasticsearch.rest.RestStatus;
  35. import org.elasticsearch.search.SearchHit;
  36. import org.elasticsearch.search.SearchHits;
  37. import org.elasticsearch.search.aggregations.AggregationBuilder;
  38. import org.elasticsearch.search.aggregations.AggregationBuilders;
  39. import org.elasticsearch.search.aggregations.Aggregations;
  40. import org.elasticsearch.search.aggregations.bucket.terms.Terms;
  41. import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
  42. import org.elasticsearch.search.aggregations.metrics.stats.ParsedStats;
  43. import org.elasticsearch.search.aggregations.metrics.tophits.ParsedTopHits;
  44. import org.elasticsearch.search.builder.SearchSourceBuilder;
  45. import org.elasticsearch.search.sort.SortOrder;
  46. import org.springframework.stereotype.Service;
  47. import javax.annotation.Resource;
  48. import java.io.IOException;
  49. import java.util.ArrayList;
  50. import java.util.Date;
  51. import java.util.List;
  52. /**
  53. * Es索引相关操作
  54. */
  55. @Service
  56. @Slf4j
  57. public class EsIndexOperationServiceImpl implements EsIndexOperationService {
  58. /**
  59. * 测试所用 ES文档id
  60. */
  61. private static final String TEST_ES_DOCUMENT_ID = "R0Xp3HsByDspl6UWckXA";
  62. /**
  63. * 查询条件的字段
  64. */
  65. private static final String TEST_ES_DOCUMENT_QUERY_KEY = "address";
  66. @Resource
  67. private RestHighLevelClient restHighLevelClient;
  68. /**
  69. * 创建索引
  70. *
  71. * @return 创建成功与否
  72. */
  73. @Override
  74. public String createIndex() {
  75. try {
  76. // 创建mapping
  77. XContentBuilder mapping = getCreateIndexMapping();
  78. // 创建索引配置信息
  79. Settings settings = Settings.builder()
  80. .put("index.number_of_shards", 1)
  81. .put("index.number_of_replicas", 0)
  82. .build();
  83. // 创建索引请求对象,然后设置索引类型(ES 7.0 将不在存在索引类型)和 mapping 与 index 配置
  84. CreateIndexRequest request = new CreateIndexRequest("test20210910", settings);
  85. request.mapping("doc", mapping);
  86. // 客户端执行创建索引的请求
  87. CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(request);
  88. // 判断是否创建成功
  89. boolean isCreated = createIndexResponse.isAcknowledged();
  90. log.info("是否创建成功:[{}]", isCreated);
  91. return isCreated ? "创建成功" : "创建失败";
  92. } catch (IOException e) {
  93. e.printStackTrace();
  94. }
  95. return null;
  96. }
  97. /**
  98. * 获取创建索引的mapping
  99. *
  100. * @return mapping
  101. * @throws IOException IO异常
  102. */
  103. private XContentBuilder getCreateIndexMapping() throws IOException {
  104. // 对比ES原生创建索引Dsl语句,每一个startObject()与endObject()就相当于Dsl语句中的一组大括号 {}
  105. return XContentFactory.jsonBuilder()
  106. .startObject()
  107. .field("dynamic", true)
  108. .startObject("properties")
  109. .startObject("name")
  110. .field("type", "text")
  111. .startObject("fields")
  112. .startObject("keyword")
  113. .field("type", "keyword")
  114. .endObject()
  115. .endObject()
  116. .endObject()
  117. .startObject("address")
  118. .field("type", "text")
  119. .startObject("fields")
  120. .startObject("keyword")
  121. .field("type", "keyword")
  122. .endObject()
  123. .endObject()
  124. .endObject()
  125. .startObject("remark")
  126. .field("type", "text")
  127. .startObject("fields")
  128. .startObject("keyword")
  129. .field("type", "keyword")
  130. .endObject()
  131. .endObject()
  132. .endObject()
  133. .startObject("sayWords")
  134. .field("type", "text")
  135. .endObject()
  136. .startObject("age")
  137. .field("type", "integer")
  138. .endObject()
  139. .startObject("salary")
  140. .field("type", "integer")
  141. .endObject()
  142. .startObject("birthDate")
  143. .field("type", "date")
  144. .field("format", "yyyy-MM-dd")
  145. .endObject()
  146. .startObject("createTime")
  147. .field("type", "date")
  148. .endObject()
  149. .endObject()
  150. .endObject();
  151. }

6.2 删除索引 

  1. /**
  2. * 删除索引
  3. *
  4. * @return 是否删除成功
  5. */
  6. @Override
  7. public String deleteIndex() {
  8. try {
  9. // 创建请求
  10. DeleteIndexRequest request = new DeleteIndexRequest("test20210910");
  11. // 处理请求
  12. DeleteIndexResponse response = restHighLevelClient.indices().delete(request);
  13. // 拿到结果
  14. boolean isDelete = response.isAcknowledged();
  15. log.info("是否删除成功:[{}]", isDelete);
  16. return isDelete ? "删除成功" : "删除失败";
  17. } catch (IOException e) {
  18. e.printStackTrace();
  19. }
  20. return null;
  21. }

6.3 新增一条文档 

  1. /**
  2. * 新增一条文档
  3. *
  4. * @return 是否新增成功
  5. */
  6. @Override
  7. public String addADocument() {
  8. // 创建请求
  9. EsDocument annotation = UserInfo.class.getAnnotation(EsDocument.class); // 获取注解
  10. IndexRequest request = new IndexRequest(annotation.index(), annotation.type());
  11. // 创建员工信息
  12. UserInfo userInfo = UserInfo.builder()
  13. .name("王五")
  14. .age(9)
  15. .salary(1100)
  16. .address("天津市")
  17. .remark("来自北京市的王先生")
  18. .sayWords("啊阿萨飒飒")
  19. .createTime(new Date())
  20. .birthday("1991-01-01").build();
  21. /*
  22. 将对象转为JSON数组
  23. 不转为JSON格式并且不声明的话会报错java.lang.IllegalArgumentException: The number of object passed must be even but was [1])
  24. 意为 request.source(userInfo) 方法不知道userInfo是什么类型的数据
  25. */
  26. byte[] json = JSON.toJSONBytes(userInfo);
  27. // 设置文档内容
  28. request.source(json, XContentType.JSON); // 声明类型
  29. try {
  30. // 执行请求
  31. IndexResponse response = restHighLevelClient.index(request);
  32. log.info("新增一条文档的结果状态:[{}]", response.status());
  33. } catch (IOException e) {
  34. e.printStackTrace();
  35. }
  36. return "新增一条文档成功";
  37. }

6.4 批量新增文档 

  1. /**
  2. * 批量新增文档
  3. *
  4. * @return 是否新增成功
  5. */
  6. @Override
  7. public String addBulkDocument() {
  8. // 创建数据集
  9. List<UserInfo> userInfoList = new ArrayList<>();
  10. for (int i = 0; i <= 10; i++) {
  11. UserInfo userInfo = UserInfo.builder()
  12. .name("用户" + i)
  13. .age(i)
  14. .salary(i * 100 + 100)
  15. .address("用户" + i + "住在" + i + "号街区")
  16. .remark("这是第" + i + "条文档信息的批量插入")
  17. .sayWords("大大慢慢那得看" + i)
  18. .createTime(new Date())
  19. .birthday("199" + i + "-01-01").build();
  20. userInfoList.add(userInfo);
  21. }
  22. // 获取注解
  23. EsDocument annotation = UserInfo.class.getAnnotation(EsDocument.class);
  24. // 创建批量插入的请求
  25. BulkRequest bulkRequest = new BulkRequest();
  26. for (UserInfo userInfo : userInfoList) {
  27. IndexRequest request = new IndexRequest(annotation.index(), annotation.type());
  28. /*
  29. * 将对象转为JSON数组
  30. 不转为JSON格式并且不声明的话会报错java.lang.IllegalArgumentException: The number of object passed must be even but was [1])
  31. 意为 request.source(userInfo) 方法不知道userInfo是什么类型的数据
  32. * */
  33. byte[] json = JSON.toJSONBytes(userInfo);
  34. request.source(json, XContentType.JSON); // 声明类型
  35. bulkRequest.add(request);
  36. }
  37. // 执行批量请求
  38. BulkResponse response = null;
  39. try {
  40. response = restHighLevelClient.bulk(bulkRequest);
  41. log.info("新增一条文档的结果状态:[{}]", response.status().getStatus());
  42. } catch (IOException e) {
  43. e.printStackTrace();
  44. }
  45. return response != null && response.status().getStatus() == 200 ? "批量新增文档成功" : "批量新增文档失败";
  46. }

6.5 更新文档 

  1. /**
  2. * 更新文档
  3. *
  4. * @return 是否更新成功
  5. */
  6. @Override
  7. public String updateDocument() {
  8. // 设置更新数据
  9. UserInfo update = UserInfo.builder().address("湖南省常德市").build();
  10. byte[] json = JSON.toJSONBytes(update);
  11. // 创建请求
  12. EsDocument annotation = UserInfo.class.getAnnotation(EsDocument.class);
  13. UpdateRequest request = new UpdateRequest(annotation.index(), annotation.type(), TEST_ES_DOCUMENT_ID);
  14. request.doc(json, XContentType.JSON);
  15. // 处理请求
  16. UpdateResponse response = null;
  17. try {
  18. response = restHighLevelClient.update(request);
  19. log.info("更新一条文档的结果状态:[{}]", response.status().getStatus());
  20. } catch (IOException e) {
  21. e.printStackTrace();
  22. }
  23. return response != null && response.status().getStatus() == 200 ? "更新成功" : "更新失败";
  24. }

6.6 删除文档

  1. /**
  2. * 删除文档
  3. *
  4. * @return 是否删除成功
  5. */
  6. @Override
  7. public String deleteDocument() {
  8. EsDocument annotation = UserInfo.class.getAnnotation(EsDocument.class);
  9. DeleteRequest request = new DeleteRequest(annotation.index(), annotation.type(), TEST_ES_DOCUMENT_ID);
  10. DeleteResponse response = null;
  11. try {
  12. response = restHighLevelClient.delete(request);
  13. log.info("删除一条文档的结果状态:[{}]", response.status().getStatus());
  14. } catch (IOException e) {
  15. e.printStackTrace();
  16. }
  17. return response != null && response.status().getStatus() == 200 ? "删除成功" : "删除失败";
  18. }

以下为各种查询操作 

6.7 根据id获取文档 

  1. /**
  2. * 根据id获取文档
  3. *
  4. * @return 文档结果
  5. */
  6. @Override
  7. public UserInfo getDocument() {
  8. EsDocument annotation = UserInfo.class.getAnnotation(EsDocument.class);
  9. GetRequest request = new GetRequest(annotation.index(), annotation.type(), TEST_ES_DOCUMENT_ID);
  10. GetResponse response = null;
  11. try {
  12. response = restHighLevelClient.get(request);
  13. log.info("根据id查询的响应体:" + response);
  14. } catch (IOException e) {
  15. e.printStackTrace();
  16. }
  17. if (response != null) {
  18. UserInfo userInfo = JSON.parseObject(response.getSourceAsBytes(), UserInfo.class);
  19. log.info("获取查询结果:" + userInfo);
  20. return BeanUtil.isEmpty(userInfo) ? null : userInfo;
  21. }
  22. return null;
  23. }

6.8 精确查询 

查询条件不会进行分词,但是查询内容可能会分词,导致查询不到

  1. /**
  2. * 精确查询(查询条件不会进行分词,但是查询内容可能会分词,导致查询不到)
  3. *
  4. * @return 查询结果
  5. */
  6. @Override
  7. public List<UserInfo> termQuery() {
  8. // 构建查询条件(注意:termQuery 支持多种格式查询,如 boolean、int、double、string 等,这里使用的是 string 的查询)
  9. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  10. searchSourceBuilder.query(QueryBuilders.termQuery(TEST_ES_DOCUMENT_QUERY_KEY + ".keyword", "用户2住在2号街区")); // 加".keyword"就是整句匹配
  11. /*
  12. * QueryBuilders 有很多查询方式,详情请查看源码
  13. * termsQuery 相当于 Mysql 的 in
  14. * searchSourceBuilder.query(QueryBuilders.termsQuery("address.keyword", "用户1住在1号街区", , "用户2住在2号街区"));
  15. *
  16. * 也可以不加 .keyword 进行模糊匹配
  17. * searchSourceBuilder.query(QueryBuilders.termsQuery("sayWords", "街", "常"));
  18. * */
  19. // 拿到索引信息
  20. EsDocument annotation = UserInfo.class.getAnnotation(EsDocument.class);
  21. // 创建查询请求,将查询对象配置到其中
  22. SearchRequest searchRequest = new SearchRequest(annotation.index());
  23. searchRequest.source(searchSourceBuilder);
  24. // 处理查询请求
  25. SearchResponse response = null;
  26. try {
  27. response = restHighLevelClient.search(searchRequest);
  28. log.info("精确查询的响应体:" + response);
  29. } catch (IOException e) {
  30. e.printStackTrace();
  31. }
  32. // 处理响应
  33. if (response != null) {
  34. if (RestStatus.OK.equals(response.status()) && response.getHits().totalHits > 0) {
  35. List<UserInfo> result = new ArrayList<>();
  36. SearchHits hits = response.getHits();
  37. for (SearchHit hit : hits) {
  38. // 将JSON转换为对象
  39. UserInfo userInfo = JSON.parseObject(hit.getSourceAsString(), UserInfo.class);
  40. result.add(userInfo);
  41. }
  42. log.info("获取查询结果:" + result);
  43. return CollectionUtil.isEmpty(result) ? null : result;
  44. }
  45. }
  46. return null;
  47. }

6.9  匹配查询符合条件的所有数据,并设置分页

  1. /**
  2. * 匹配查询符合条件的所有数据,并设置分页
  3. *
  4. * @return 查询结果
  5. */
  6. @Override
  7. public List<UserInfo> matchAllQuery() {
  8. // 创建匹配全部的查询条件
  9. MatchAllQueryBuilder matchAllQueryBuilder = QueryBuilders.matchAllQuery();
  10. /*
  11. * 创建匹配筛选的查询条件
  12. * MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery(TEST_ES_DOCUMENT_QUERY_KEY, "*街区");
  13. *
  14. * 创建匹配短句的查询条件
  15. * MatchPhraseQueryBuilder matchPhraseQueryBuilder = QueryBuilders.matchPhraseQuery(TEST_ES_DOCUMENT_QUERY_KEY, "用户");
  16. *
  17. * 创建根据内容匹配多个字段的查询条件
  18. * MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders.multiMatchQuery("北京", TEST_ES_DOCUMENT_QUERY_KEY, "remark");
  19. * */
  20. // 创建查询源构造器
  21. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  22. searchSourceBuilder.query(matchAllQueryBuilder);
  23. // 设置分页
  24. searchSourceBuilder.from(0);
  25. searchSourceBuilder.size(10);
  26. // 设置排序
  27. searchSourceBuilder.sort("salary", SortOrder.DESC);
  28. // 创建请求,并将查询条件配置到其中
  29. EsDocument annotation = UserInfo.class.getAnnotation(EsDocument.class);
  30. SearchRequest request = new SearchRequest(annotation.index());
  31. request.source(searchSourceBuilder);
  32. // 处理查询请求
  33. SearchResponse response = null;
  34. try {
  35. response = restHighLevelClient.search(request);
  36. log.info("匹配所有条件查询的响应体:" + response);
  37. } catch (IOException e) {
  38. e.printStackTrace();
  39. }
  40. // 处理响应
  41. if (response != null) {
  42. if (RestStatus.OK.equals(response.status()) && response.getHits().totalHits > 0) {
  43. List<UserInfo> result = new ArrayList<>();
  44. for (SearchHit hit : response.getHits()) {
  45. // 将JSON转化为对象
  46. UserInfo userInfo = JSON.parseObject(hit.getSourceAsString(), UserInfo.class);
  47. result.add(userInfo);
  48. }
  49. log.info("获取查询结果:" + result);
  50. return CollectionUtil.isEmpty(result) ? null : result;
  51. }
  52. }
  53. return null;
  54. }

6.10 模糊查询 (慎用)

  1. /**
  2. * 模糊查询
  3. *
  4. * 慎用!!
  5. *
  6. * @return 查询结果
  7. */
  8. @Override
  9. public List<UserInfo> fuzzyQuery() {
  10. // 设置筛选条件,并设置模糊性(越大匹配度越低,注意:模糊度没设置合适可能会出现不想要的结果甚至无结果) 慎用!!
  11. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  12. searchSourceBuilder.query(QueryBuilders.fuzzyQuery(TEST_ES_DOCUMENT_QUERY_KEY, "街区").fuzziness(Fuzziness.ONE));
  13. // 创建请求
  14. EsDocument annotation = UserInfo.class.getAnnotation(EsDocument.class);
  15. SearchRequest searchRequest = new SearchRequest(annotation.index());
  16. searchRequest.source(searchSourceBuilder);
  17. // 处理请求
  18. SearchResponse response = null;
  19. try {
  20. response = restHighLevelClient.search(searchRequest);
  21. log.info("模糊查询查询的响应体:" + response);
  22. } catch (IOException e) {
  23. e.printStackTrace();
  24. }
  25. // 处理响应
  26. if (response != null) {
  27. if (RestStatus.OK.equals(response.status()) && response.getHits().totalHits > 0) {
  28. List<UserInfo> result = new ArrayList<>();
  29. for (SearchHit hit : response.getHits()) {
  30. UserInfo userInfo = JSON.parseObject(hit.getSourceAsString(), UserInfo.class);
  31. result.add(userInfo);
  32. }
  33. log.info("获取查询结果:" + result);
  34. return result;
  35. }
  36. }
  37. return null;
  38. }

6.11 范围查询 

  1. /**
  2. * 范围查询
  3. *
  4. * @return 查询结果
  5. */
  6. @Override
  7. public List<UserInfo> rangeQuery() {
  8. // 设置查询条件,includeLower(是否包含下边界)、includeUpper(是否包含上边界)
  9. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  10. searchSourceBuilder.query(QueryBuilders.rangeQuery("salary").gte(500).lte(1000).includeLower(true).includeUpper(true));
  11. /*
  12. 如果查询的字段是日期类型
  13. searchSourceBuilder.query(QueryBuilders.rangeQuery("birthday").from("1991-01-01").to("1999-01-01").includeLower(true).includeUpper(true));
  14. */
  15. // 创建请求
  16. EsDocument annotation = UserInfo.class.getAnnotation(EsDocument.class);
  17. SearchRequest request = new SearchRequest(annotation.index());
  18. request.source(searchSourceBuilder);
  19. // 处理请求
  20. SearchResponse response = null;
  21. try {
  22. response = restHighLevelClient.search(request);
  23. log.info("范围查询的响应体:" + response);
  24. } catch (IOException e) {
  25. e.printStackTrace();
  26. }
  27. // 处理响应
  28. if (response != null) {
  29. if (RestStatus.OK.equals(response.status()) && response.getHits().totalHits > 0) {
  30. List<UserInfo> result = new ArrayList<>();
  31. for (SearchHit hit : response.getHits()) {
  32. UserInfo userInfo = JSON.parseObject(hit.getSourceAsString(), UserInfo.class);
  33. result.add(userInfo);
  34. }
  35. log.info("获取查询结果:" + result);
  36. return result;
  37. }
  38. }
  39. return null;
  40. }

6.12 通配符查询

*:表示多个字符(0个或多个字符)  ?:表示单个字符 

  1. /**
  2. * 通配符查询( *:表示多个字符(0个或多个字符) ?:表示单个字符)
  3. *
  4. * @return 查询结果
  5. */
  6. @Override
  7. public List<UserInfo> wildcardQuery() {
  8. // 创建查询条件
  9. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  10. searchSourceBuilder.query(QueryBuilders.wildcardQuery(TEST_ES_DOCUMENT_QUERY_KEY + ".keyword", "*街区"));
  11. // 创建请求
  12. EsDocument annotation = UserInfo.class.getAnnotation(EsDocument.class);
  13. SearchRequest request = new SearchRequest(annotation.index());
  14. request.source(searchSourceBuilder);
  15. // 处理请求
  16. SearchResponse response = null;
  17. try {
  18. response = restHighLevelClient.search(request);
  19. log.info("通配符查询的响应体:" + response);
  20. } catch (IOException e) {
  21. e.printStackTrace();
  22. }
  23. // 处理响应
  24. if (response != null) {
  25. if (RestStatus.OK.equals(response.status()) && response.getHits().totalHits > 0) {
  26. List<UserInfo> result = new ArrayList<>();
  27. for (SearchHit hit : response.getHits()) {
  28. UserInfo userInfo = JSON.parseObject(hit.getSourceAsString(), UserInfo.class);
  29. result.add(userInfo);
  30. }
  31. log.info("获取查询结果:" + result);
  32. return result;
  33. }
  34. }
  35. return null;
  36. }

6.13 布尔查询(重点!) 

  1. /**
  2. * 布尔查询(重点!)
  3. *
  4. * @return 查询结果
  5. */
  6. @Override
  7. public List<UserInfo> boolQuery() {
  8. // 创建bool查询构建器
  9. BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
  10. // 创建查询条件(若有多个条件,就让后面接着加)
  11. boolQueryBuilder.must(QueryBuilders.termsQuery(TEST_ES_DOCUMENT_QUERY_KEY + ".keyword", "用户2住在2号街区", "用户3住在3号街区", "用户8住在8号街区"))
  12. .filter().add(QueryBuilders.rangeQuery("birthday").format("yyyy").gte("1990").lte("1995").includeLower(true).includeUpper(true));
  13. // 创建查询源并将构建器配置其中
  14. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  15. searchSourceBuilder.query(boolQueryBuilder);
  16. // 创建请求
  17. EsDocument annotation = UserInfo.class.getAnnotation(EsDocument.class);
  18. SearchRequest request = new SearchRequest(annotation.index());
  19. request.source(searchSourceBuilder);
  20. // 处理请求
  21. SearchResponse response = null;
  22. try {
  23. response = restHighLevelClient.search(request);
  24. log.info("布尔查询的响应体:" + response);
  25. } catch (IOException e) {
  26. e.printStackTrace();
  27. }
  28. // 处理响应
  29. if (response != null) {
  30. if (RestStatus.OK.equals(response.status()) && response.getHits().totalHits > 0) {
  31. List<UserInfo> result = new ArrayList<>();
  32. for (SearchHit hit : response.getHits()) {
  33. UserInfo userInfo = JSON.parseObject(hit.getSourceAsString(), UserInfo.class);
  34. result.add(userInfo);
  35. }
  36. log.info("获取查询结果:" + result);
  37. return result;
  38. }
  39. }
  40. return null;
  41. }

6.14 聚合统计查询(重点!) 

  1. /**
  2. * 聚合统计查询(重点!)
  3. *
  4. * @return 查询结果如下:
  5. * {
  6. * "salary_stats": {
  7. * "name": "salary_stats",
  8. * "count": 26,
  9. * "min": 100.0,
  10. * "max": 1100.0,
  11. * "sum": 12100.0,
  12. * "avg": 465.38461538461536,
  13. * "type": "stats",
  14. * "sumAsString": "12100.0",
  15. * "maxAsString": "1100.0",
  16. * "avgAsString": "465.38461538461536",
  17. * "minAsString": "100.0",
  18. * "metaData": null,
  19. * "fragment": true
  20. * }
  21. * }
  22. */
  23. @Override
  24. public Object aggregationStats() {
  25. /*
  26. 声明聚合的类型与字段
  27. 统计数据(可拿到总数、平均数、最大值、最小值等数据) -- stats("字段_stats").field("字段")
  28. 总数 -- count("字段_count").field("字段")
  29. 平均数 -- avg("字段_avg").field("字段")
  30. 以此类推...
  31. */
  32. AggregationBuilder aggr = AggregationBuilders.stats("salary_stats").field("salary");
  33. // 设置查询条件
  34. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  35. searchSourceBuilder.aggregation(aggr);
  36. // 设置查询结果不返回,只返回聚合的结果
  37. searchSourceBuilder.size(0);
  38. // 创建请求
  39. EsDocument annotation = UserInfo.class.getAnnotation(EsDocument.class);
  40. SearchRequest request = new SearchRequest(annotation.index());
  41. request.source(searchSourceBuilder);
  42. // 处理请求
  43. SearchResponse response = null;
  44. try {
  45. response = restHighLevelClient.search(request);
  46. log.info("聚合统计查询的响应体:" + response);
  47. } catch (IOException e) {
  48. e.printStackTrace();
  49. }
  50. // 处理响应
  51. if (response != null) {
  52. // 获取响应中的聚合信息
  53. Aggregations aggregations = response.getAggregations();
  54. if (RestStatus.OK.equals(response.status()) && aggregations != null) {
  55. /*
  56. 解析数据类型
  57. ParsedStats -- 聚合信息
  58. ParsedValueCount -- 总数
  59. ParsedAvg -- 平均数
  60. 以此类推
  61. */
  62. ParsedStats stats = aggregations.get("salary_stats");
  63. log.info("-------------------------------------------");
  64. log.info("聚合信息:");
  65. log.info("count:{}", stats.getCount());
  66. log.info("avg:{}", stats.getAvg());
  67. log.info("max:{}", stats.getMax());
  68. log.info("min:{}", stats.getMin());
  69. log.info("sum:{}", stats.getSum());
  70. log.info("-------------------------------------------");
  71. return aggregations.getAsMap();
  72. }
  73. }
  74. return null;
  75. }

6.15 聚合分桶查询(重点!) 

  1. /**
  2. * 聚合分桶查询(重点!)
  3. *
  4. * @return 查询结果: 桶名 与 对应的总数
  5. */
  6. @Override
  7. public Object aggregationBucket() {
  8. /*
  9. < 声明聚合的类型与字段 >
  10. 按岁数进行聚合分桶
  11. TermsAggregationBuilder aggr = AggregationBuilders.terms("age_bucket").field("age");
  12. 按工资范围进行聚合分桶
  13. AggregationBuilder aggr = AggregationBuilders.range("salary_range_bucket")
  14. .field("salary")
  15. .addUnboundedTo("低级员工", 3000)
  16. .addRange("中级员工", 5000, 9000)
  17. .addUnboundedFrom("高级员工", 9000);
  18. 按照时间范围进行分桶
  19. AggregationBuilder aggr = AggregationBuilders.dateRange("date_range_bucket")
  20. .field("birthday")
  21. .format("yyyy")
  22. .addRange("1985-1990", "1985", "1990")
  23. .addRange("1990-1995", "1990", "1995");
  24. 按工资多少进行聚合分桶
  25. AggregationBuilder aggr = AggregationBuilders.histogram("salary_histogram")
  26. .field("salary")
  27. .extendedBounds(0, 12000)
  28. .interval(3000);
  29. 按出生日期进行分桶
  30. AggregationBuilder aggr = AggregationBuilders.dateHistogram("birthday_histogram")
  31. .field("birthday")
  32. .interval(1)
  33. .dateHistogramInterval(DateHistogramInterval.YEAR)
  34. .format("yyyy");
  35. */
  36. TermsAggregationBuilder aggr = AggregationBuilders.terms("age_bucket").field("age");
  37. // 创建查询条件
  38. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  39. searchSourceBuilder.aggregation(aggr);
  40. searchSourceBuilder.size(10);
  41. // 创建请求
  42. EsDocument annotation = UserInfo.class.getAnnotation(EsDocument.class);
  43. SearchRequest request = new SearchRequest(annotation.index());
  44. request.source(searchSourceBuilder);
  45. // 处理请求
  46. SearchResponse response = null;
  47. try {
  48. response = restHighLevelClient.search(request);
  49. log.info("聚合分桶查询的响应体:" + response);
  50. } catch (IOException e) {
  51. e.printStackTrace();
  52. }
  53. // 处理响应
  54. if (response != null) {
  55. if (RestStatus.OK.equals(response.status())) {
  56. // 获取响应中的聚合信息
  57. Aggregations aggregations = response.getAggregations();
  58. // 分桶
  59. Terms byCompanyAggregation = aggregations.get("age_bucket"); // 不同的聚合类型修改 声明聚合的类型与字段 中AggregationBuilders的不同名称即可
  60. List<? extends Terms.Bucket> buckets = byCompanyAggregation.getBuckets();
  61. // 输出各个桶的内容
  62. log.info("-------------------------------------------");
  63. log.info("聚合信息:");
  64. for (Terms.Bucket bucket : buckets) {
  65. log.info("桶名:{} | 总数:{}", bucket.getKeyAsString(), bucket.getDocCount());
  66. }
  67. log.info("-------------------------------------------");
  68. return aggregations.getAsMap();
  69. }
  70. }
  71. return null;
  72. }

6.16 聚合查询场景分析

按岁数分桶、然后统计各个岁数收入最高的用户信息 

  1. /**
  2. * 聚合查询场景分析
  3. * (按岁数分桶、然后统计各个岁数收入最高的用户信息)
  4. *
  5. * @return 查询结果:
  6. * 桶名:1
  7. * 值:{"address":"湖南省常德市","age":1,"birthday":"1991-01-01","createTime":1631498892472,"name":"用户1","remark":"这是第1条文档信息的批量插入","salary":200}
  8. *
  9. * 以此类推...
  10. */
  11. @Override
  12. public Object aggregationAnalysis() {
  13. // 构建聚合参数
  14. AggregationBuilder testTop = AggregationBuilders.topHits("salary_max_user")
  15. .size(1)
  16. .sort("salary", SortOrder.DESC);
  17. AggregationBuilder salaryBucket = AggregationBuilders.terms("salary_bucket")
  18. .field("age")
  19. .size(10);
  20. salaryBucket.subAggregation(testTop);
  21. // 创建查询条件
  22. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  23. searchSourceBuilder.size(0);
  24. searchSourceBuilder.aggregation(salaryBucket);
  25. // 创建请求
  26. EsDocument annotation = UserInfo.class.getAnnotation(EsDocument.class);
  27. SearchRequest request = new SearchRequest(annotation.index());
  28. request.source(searchSourceBuilder);
  29. // 处理请求
  30. SearchResponse response = null;
  31. try {
  32. response = restHighLevelClient.search(request);
  33. log.info("聚合查询场景分析的响应体:" + response);
  34. } catch (IOException e) {
  35. e.printStackTrace();
  36. }
  37. // 处理响应
  38. if (response != null) {
  39. // 获取响应中的聚合信息
  40. Aggregations aggregations = response.getAggregations();
  41. if (RestStatus.OK.equals(response.status())) {
  42. // 分桶
  43. Terms byCompanyAggregation = aggregations.get("salary_bucket");
  44. List<? extends Terms.Bucket> buckets = byCompanyAggregation.getBuckets();
  45. // 输出各个桶的内容
  46. log.info("-------------------------------------------");
  47. log.info("聚合信息:");
  48. for (Terms.Bucket bucket : buckets) {
  49. log.info("桶名:{}", bucket.getKeyAsString());
  50. ParsedTopHits topHits = bucket.getAggregations().get("salary_max_user");
  51. for (SearchHit hit:topHits.getHits()){
  52. log.info(hit.getSourceAsString());
  53. }
  54. }
  55. log.info("-------------------------------------------");
  56. return aggregations.getAsMap();
  57. }
  58. }
  59. return response;
  60. }
  61. }

第六步中所有代码(方便一次性粘贴)

  1. package com.es.example.service.impl;
  2. import cn.hutool.core.bean.BeanUtil;
  3. import cn.hutool.core.collection.CollectionUtil;
  4. import com.alibaba.fastjson.JSON;
  5. import com.es.example.annotations.EsDocument;
  6. import com.es.example.entity.UserInfo;
  7. import com.es.example.service.EsIndexOperationService;
  8. import lombok.extern.slf4j.Slf4j;
  9. import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
  10. import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
  11. import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
  12. import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse;
  13. import org.elasticsearch.action.bulk.BulkRequest;
  14. import org.elasticsearch.action.bulk.BulkResponse;
  15. import org.elasticsearch.action.delete.DeleteRequest;
  16. import org.elasticsearch.action.delete.DeleteResponse;
  17. import org.elasticsearch.action.get.GetRequest;
  18. import org.elasticsearch.action.get.GetResponse;
  19. import org.elasticsearch.action.index.IndexRequest;
  20. import org.elasticsearch.action.index.IndexResponse;
  21. import org.elasticsearch.action.search.SearchRequest;
  22. import org.elasticsearch.action.search.SearchResponse;
  23. import org.elasticsearch.action.update.UpdateRequest;
  24. import org.elasticsearch.action.update.UpdateResponse;
  25. import org.elasticsearch.client.RestHighLevelClient;
  26. import org.elasticsearch.common.settings.Settings;
  27. import org.elasticsearch.common.unit.Fuzziness;
  28. import org.elasticsearch.common.xcontent.XContentBuilder;
  29. import org.elasticsearch.common.xcontent.XContentFactory;
  30. import org.elasticsearch.common.xcontent.XContentType;
  31. import org.elasticsearch.index.query.BoolQueryBuilder;
  32. import org.elasticsearch.index.query.MatchAllQueryBuilder;
  33. import org.elasticsearch.index.query.QueryBuilders;
  34. import org.elasticsearch.rest.RestStatus;
  35. import org.elasticsearch.search.SearchHit;
  36. import org.elasticsearch.search.SearchHits;
  37. import org.elasticsearch.search.aggregations.AggregationBuilder;
  38. import org.elasticsearch.search.aggregations.AggregationBuilders;
  39. import org.elasticsearch.search.aggregations.Aggregations;
  40. import org.elasticsearch.search.aggregations.bucket.terms.Terms;
  41. import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
  42. import org.elasticsearch.search.aggregations.metrics.stats.ParsedStats;
  43. import org.elasticsearch.search.aggregations.metrics.tophits.ParsedTopHits;
  44. import org.elasticsearch.search.builder.SearchSourceBuilder;
  45. import org.elasticsearch.search.sort.SortOrder;
  46. import org.springframework.stereotype.Service;
  47. import javax.annotation.Resource;
  48. import java.io.IOException;
  49. import java.util.ArrayList;
  50. import java.util.Date;
  51. import java.util.List;
  52. /**
  53. * Es索引相关操作
  54. */
  55. @Service
  56. @Slf4j
  57. public class EsIndexOperationServiceImpl implements EsIndexOperationService {
  58. /**
  59. * 测试所用 ES文档id
  60. */
  61. private static final String TEST_ES_DOCUMENT_ID = "R0Xp3HsByDspl6UWckXA";
  62. /**
  63. * 查询条件的字段
  64. */
  65. private static final String TEST_ES_DOCUMENT_QUERY_KEY = "address";
  66. @Resource
  67. private RestHighLevelClient restHighLevelClient;
  68. /**
  69. * 创建索引
  70. *
  71. * @return 创建成功与否
  72. */
  73. @Override
  74. public String createIndex() {
  75. try {
  76. // 创建mapping
  77. XContentBuilder mapping = getCreateIndexMapping();
  78. // 创建索引配置信息
  79. Settings settings = Settings.builder()
  80. .put("index.number_of_shards", 1)
  81. .put("index.number_of_replicas", 0)
  82. .build();
  83. // 创建索引请求对象,然后设置索引类型(ES 7.0 将不在存在索引类型)和 mapping 与 index 配置
  84. CreateIndexRequest request = new CreateIndexRequest("test20210910", settings);
  85. request.mapping("doc", mapping);
  86. // 客户端执行创建索引的请求
  87. CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(request);
  88. // 判断是否创建成功
  89. boolean isCreated = createIndexResponse.isAcknowledged();
  90. log.info("是否创建成功:[{}]", isCreated);
  91. return isCreated ? "创建成功" : "创建失败";
  92. } catch (IOException e) {
  93. e.printStackTrace();
  94. }
  95. return null;
  96. }
  97. /**
  98. * 获取创建索引的mapping
  99. *
  100. * @return mapping
  101. * @throws IOException IO异常
  102. */
  103. private XContentBuilder getCreateIndexMapping() throws IOException {
  104. // 对比ES原生创建索引Dsl语句,每一个startObject()与endObject()就相当于Dsl语句中的一组大括号 {}
  105. return XContentFactory.jsonBuilder()
  106. .startObject()
  107. .field("dynamic", true)
  108. .startObject("properties")
  109. .startObject("name")
  110. .field("type", "text")
  111. .startObject("fields")
  112. .startObject("keyword")
  113. .field("type", "keyword")
  114. .endObject()
  115. .endObject()
  116. .endObject()
  117. .startObject("address")
  118. .field("type", "text")
  119. .startObject("fields")
  120. .startObject("keyword")
  121. .field("type", "keyword")
  122. .endObject()
  123. .endObject()
  124. .endObject()
  125. .startObject("remark")
  126. .field("type", "text")
  127. .startObject("fields")
  128. .startObject("keyword")
  129. .field("type", "keyword")
  130. .endObject()
  131. .endObject()
  132. .endObject()
  133. .startObject("sayWords")
  134. .field("type", "text")
  135. .endObject()
  136. .startObject("age")
  137. .field("type", "integer")
  138. .endObject()
  139. .startObject("salary")
  140. .field("type", "integer")
  141. .endObject()
  142. .startObject("birthDate")
  143. .field("type", "date")
  144. .field("format", "yyyy-MM-dd")
  145. .endObject()
  146. .startObject("createTime")
  147. .field("type", "date")
  148. .endObject()
  149. .endObject()
  150. .endObject();
  151. }
  152. /**
  153. * 删除索引
  154. *
  155. * @return 是否删除成功
  156. */
  157. @Override
  158. public String deleteIndex() {
  159. try {
  160. // 创建请求
  161. DeleteIndexRequest request = new DeleteIndexRequest("test20210910");
  162. // 处理请求
  163. DeleteIndexResponse response = restHighLevelClient.indices().delete(request);
  164. // 拿到结果
  165. boolean isDelete = response.isAcknowledged();
  166. log.info("是否删除成功:[{}]", isDelete);
  167. return isDelete ? "删除成功" : "删除失败";
  168. } catch (IOException e) {
  169. e.printStackTrace();
  170. }
  171. return null;
  172. }
  173. /**
  174. * 新增一条文档
  175. *
  176. * @return 是否新增成功
  177. */
  178. @Override
  179. public String addADocument() {
  180. // 创建请求
  181. EsDocument annotation = UserInfo.class.getAnnotation(EsDocument.class); // 获取注解
  182. IndexRequest request = new IndexRequest(annotation.index(), annotation.type());
  183. // 创建员工信息
  184. UserInfo userInfo = UserInfo.builder()
  185. .name("王五")
  186. .age(9)
  187. .salary(1100)
  188. .address("天津市")
  189. .remark("来自北京市的王先生")
  190. .sayWords("啊阿萨飒飒")
  191. .createTime(new Date())
  192. .birthday("1991-01-01").build();
  193. /*
  194. 将对象转为JSON数组
  195. 不转为JSON格式并且不声明的话会报错java.lang.IllegalArgumentException: The number of object passed must be even but was [1])
  196. 意为 request.source(userInfo) 方法不知道userInfo是什么类型的数据
  197. */
  198. byte[] json = JSON.toJSONBytes(userInfo);
  199. // 设置文档内容
  200. request.source(json, XContentType.JSON); // 声明类型
  201. try {
  202. // 执行请求
  203. IndexResponse response = restHighLevelClient.index(request);
  204. log.info("新增一条文档的结果状态:[{}]", response.status());
  205. } catch (IOException e) {
  206. e.printStackTrace();
  207. }
  208. return "新增一条文档成功";
  209. }
  210. /**
  211. * 批量新增文档
  212. *
  213. * @return 是否新增成功
  214. */
  215. @Override
  216. public String addBulkDocument() {
  217. // 创建数据集
  218. List<UserInfo> userInfoList = new ArrayList<>();
  219. for (int i = 0; i <= 10; i++) {
  220. UserInfo userInfo = UserInfo.builder()
  221. .name("用户" + i)
  222. .age(i)
  223. .salary(i * 100 + 100)
  224. .address("用户" + i + "住在" + i + "号街区")
  225. .remark("这是第" + i + "条文档信息的批量插入")
  226. .sayWords("大大慢慢那得看" + i)
  227. .createTime(new Date())
  228. .birthday("199" + i + "-01-01").build();
  229. userInfoList.add(userInfo);
  230. }
  231. // 获取注解
  232. EsDocument annotation = UserInfo.class.getAnnotation(EsDocument.class);
  233. // 创建批量插入的请求
  234. BulkRequest bulkRequest = new BulkRequest();
  235. for (UserInfo userInfo : userInfoList) {
  236. IndexRequest request = new IndexRequest(annotation.index(), annotation.type());
  237. /*
  238. * 将对象转为JSON数组
  239. 不转为JSON格式并且不声明的话会报错java.lang.IllegalArgumentException: The number of object passed must be even but was [1])
  240. 意为 request.source(userInfo) 方法不知道userInfo是什么类型的数据
  241. * */
  242. byte[] json = JSON.toJSONBytes(userInfo);
  243. request.source(json, XContentType.JSON); // 声明类型
  244. bulkRequest.add(request);
  245. }
  246. // 执行批量请求
  247. BulkResponse response = null;
  248. try {
  249. response = restHighLevelClient.bulk(bulkRequest);
  250. log.info("新增一条文档的结果状态:[{}]", response.status().getStatus());
  251. } catch (IOException e) {
  252. e.printStackTrace();
  253. }
  254. return response != null && response.status().getStatus() == 200 ? "批量新增文档成功" : "批量新增文档失败";
  255. }
  256. /**
  257. * 更新文档
  258. *
  259. * @return 是否更新成功
  260. */
  261. @Override
  262. public String updateDocument() {
  263. // 设置更新数据
  264. UserInfo update = UserInfo.builder().address("湖南省常德市").build();
  265. byte[] json = JSON.toJSONBytes(update);
  266. // 创建请求
  267. EsDocument annotation = UserInfo.class.getAnnotation(EsDocument.class);
  268. UpdateRequest request = new UpdateRequest(annotation.index(), annotation.type(), TEST_ES_DOCUMENT_ID);
  269. request.doc(json, XContentType.JSON);
  270. // 处理请求
  271. UpdateResponse response = null;
  272. try {
  273. response = restHighLevelClient.update(request);
  274. log.info("更新一条文档的结果状态:[{}]", response.status().getStatus());
  275. } catch (IOException e) {
  276. e.printStackTrace();
  277. }
  278. return response != null && response.status().getStatus() == 200 ? "更新成功" : "更新失败";
  279. }
  280. /**
  281. * 删除文档
  282. *
  283. * @return 是否删除成功
  284. */
  285. @Override
  286. public String deleteDocument() {
  287. EsDocument annotation = UserInfo.class.getAnnotation(EsDocument.class);
  288. DeleteRequest request = new DeleteRequest(annotation.index(), annotation.type(), TEST_ES_DOCUMENT_ID);
  289. DeleteResponse response = null;
  290. try {
  291. response = restHighLevelClient.delete(request);
  292. log.info("删除一条文档的结果状态:[{}]", response.status().getStatus());
  293. } catch (IOException e) {
  294. e.printStackTrace();
  295. }
  296. return response != null && response.status().getStatus() == 200 ? "删除成功" : "删除失败";
  297. }
  298. /* >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 以下为查询操作示例 <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< */
  299. /**
  300. * 根据id获取文档
  301. *
  302. * @return 文档结果
  303. */
  304. @Override
  305. public UserInfo getDocument() {
  306. EsDocument annotation = UserInfo.class.getAnnotation(EsDocument.class);
  307. GetRequest request = new GetRequest(annotation.index(), annotation.type(), TEST_ES_DOCUMENT_ID);
  308. GetResponse response = null;
  309. try {
  310. response = restHighLevelClient.get(request);
  311. log.info("根据id查询的响应体:" + response);
  312. } catch (IOException e) {
  313. e.printStackTrace();
  314. }
  315. if (response != null) {
  316. UserInfo userInfo = JSON.parseObject(response.getSourceAsBytes(), UserInfo.class);
  317. log.info("获取查询结果:" + userInfo);
  318. return BeanUtil.isEmpty(userInfo) ? null : userInfo;
  319. }
  320. return null;
  321. }
  322. /**
  323. * 精确查询(查询条件不会进行分词,但是查询内容可能会分词,导致查询不到)
  324. *
  325. * @return 查询结果
  326. */
  327. @Override
  328. public List<UserInfo> termQuery() {
  329. // 构建查询条件(注意:termQuery 支持多种格式查询,如 boolean、int、double、string 等,这里使用的是 string 的查询)
  330. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  331. searchSourceBuilder.query(QueryBuilders.termQuery(TEST_ES_DOCUMENT_QUERY_KEY + ".keyword", "用户2住在2号街区")); // 加".keyword"就是整句匹配
  332. /*
  333. * QueryBuilders 有很多查询方式,详情请查看源码
  334. * termsQuery 相当于 Mysql 的 in
  335. * searchSourceBuilder.query(QueryBuilders.termsQuery("address.keyword", "用户1住在1号街区", , "用户2住在2号街区"));
  336. *
  337. * 也可以不加 .keyword 进行模糊匹配
  338. * searchSourceBuilder.query(QueryBuilders.termsQuery("sayWords", "街", "常"));
  339. * */
  340. // 拿到索引信息
  341. EsDocument annotation = UserInfo.class.getAnnotation(EsDocument.class);
  342. // 创建查询请求,将查询对象配置到其中
  343. SearchRequest searchRequest = new SearchRequest(annotation.index());
  344. searchRequest.source(searchSourceBuilder);
  345. // 处理查询请求
  346. SearchResponse response = null;
  347. try {
  348. response = restHighLevelClient.search(searchRequest);
  349. log.info("精确查询的响应体:" + response);
  350. } catch (IOException e) {
  351. e.printStackTrace();
  352. }
  353. // 处理响应
  354. if (response != null) {
  355. if (RestStatus.OK.equals(response.status()) && response.getHits().totalHits > 0) {
  356. List<UserInfo> result = new ArrayList<>();
  357. SearchHits hits = response.getHits();
  358. for (SearchHit hit : hits) {
  359. // 将JSON转换为对象
  360. UserInfo userInfo = JSON.parseObject(hit.getSourceAsString(), UserInfo.class);
  361. result.add(userInfo);
  362. }
  363. log.info("获取查询结果:" + result);
  364. return CollectionUtil.isEmpty(result) ? null : result;
  365. }
  366. }
  367. return null;
  368. }
  369. /**
  370. * 匹配查询符合条件的所有数据,并设置分页
  371. *
  372. * @return 查询结果
  373. */
  374. @Override
  375. public List<UserInfo> matchAllQuery() {
  376. // 创建匹配全部的查询条件
  377. MatchAllQueryBuilder matchAllQueryBuilder = QueryBuilders.matchAllQuery();
  378. /*
  379. * 创建匹配筛选的查询条件
  380. * MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery(TEST_ES_DOCUMENT_QUERY_KEY, "*街区");
  381. *
  382. * 创建匹配短句的查询条件
  383. * MatchPhraseQueryBuilder matchPhraseQueryBuilder = QueryBuilders.matchPhraseQuery(TEST_ES_DOCUMENT_QUERY_KEY, "用户");
  384. *
  385. * 创建根据内容匹配多个字段的查询条件
  386. * MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders.multiMatchQuery("北京", TEST_ES_DOCUMENT_QUERY_KEY, "remark");
  387. * */
  388. // 创建查询源构造器
  389. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  390. searchSourceBuilder.query(matchAllQueryBuilder);
  391. // 设置分页
  392. searchSourceBuilder.from(0);
  393. searchSourceBuilder.size(10);
  394. // 设置排序
  395. searchSourceBuilder.sort("salary", SortOrder.DESC);
  396. // 创建请求,并将查询条件配置到其中
  397. EsDocument annotation = UserInfo.class.getAnnotation(EsDocument.class);
  398. SearchRequest request = new SearchRequest(annotation.index());
  399. request.source(searchSourceBuilder);
  400. // 处理查询请求
  401. SearchResponse response = null;
  402. try {
  403. response = restHighLevelClient.search(request);
  404. log.info("匹配所有条件查询的响应体:" + response);
  405. } catch (IOException e) {
  406. e.printStackTrace();
  407. }
  408. // 处理响应
  409. if (response != null) {
  410. if (RestStatus.OK.equals(response.status()) && response.getHits().totalHits > 0) {
  411. List<UserInfo> result = new ArrayList<>();
  412. for (SearchHit hit : response.getHits()) {
  413. // 将JSON转化为对象
  414. UserInfo userInfo = JSON.parseObject(hit.getSourceAsString(), UserInfo.class);
  415. result.add(userInfo);
  416. }
  417. log.info("获取查询结果:" + result);
  418. return CollectionUtil.isEmpty(result) ? null : result;
  419. }
  420. }
  421. return null;
  422. }
  423. /**
  424. * 模糊查询
  425. *
  426. * 慎用!!
  427. *
  428. * @return 查询结果
  429. */
  430. @Override
  431. public List<UserInfo> fuzzyQuery() {
  432. // 设置筛选条件,并设置模糊性(越大匹配度越低,注意:模糊度没设置合适可能会出现不想要的结果甚至无结果) 慎用!!
  433. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  434. searchSourceBuilder.query(QueryBuilders.fuzzyQuery(TEST_ES_DOCUMENT_QUERY_KEY, "街区").fuzziness(Fuzziness.ONE));
  435. // 创建请求
  436. EsDocument annotation = UserInfo.class.getAnnotation(EsDocument.class);
  437. SearchRequest searchRequest = new SearchRequest(annotation.index());
  438. searchRequest.source(searchSourceBuilder);
  439. // 处理请求
  440. SearchResponse response = null;
  441. try {
  442. response = restHighLevelClient.search(searchRequest);
  443. log.info("模糊查询查询的响应体:" + response);
  444. } catch (IOException e) {
  445. e.printStackTrace();
  446. }
  447. // 处理响应
  448. if (response != null) {
  449. if (RestStatus.OK.equals(response.status()) && response.getHits().totalHits > 0) {
  450. List<UserInfo> result = new ArrayList<>();
  451. for (SearchHit hit : response.getHits()) {
  452. UserInfo userInfo = JSON.parseObject(hit.getSourceAsString(), UserInfo.class);
  453. result.add(userInfo);
  454. }
  455. log.info("获取查询结果:" + result);
  456. return result;
  457. }
  458. }
  459. return null;
  460. }
  461. /**
  462. * 范围查询
  463. *
  464. * @return 查询结果
  465. */
  466. @Override
  467. public List<UserInfo> rangeQuery() {
  468. // 设置查询条件,includeLower(是否包含下边界)、includeUpper(是否包含上边界)
  469. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  470. searchSourceBuilder.query(QueryBuilders.rangeQuery("salary").gte(500).lte(1000).includeLower(true).includeUpper(true));
  471. /*
  472. 如果查询的字段是日期类型
  473. searchSourceBuilder.query(QueryBuilders.rangeQuery("birthday").from("1991-01-01").to("1999-01-01").includeLower(true).includeUpper(true));
  474. */
  475. // 创建请求
  476. EsDocument annotation = UserInfo.class.getAnnotation(EsDocument.class);
  477. SearchRequest request = new SearchRequest(annotation.index());
  478. request.source(searchSourceBuilder);
  479. // 处理请求
  480. SearchResponse response = null;
  481. try {
  482. response = restHighLevelClient.search(request);
  483. log.info("范围查询的响应体:" + response);
  484. } catch (IOException e) {
  485. e.printStackTrace();
  486. }
  487. // 处理响应
  488. if (response != null) {
  489. if (RestStatus.OK.equals(response.status()) && response.getHits().totalHits > 0) {
  490. List<UserInfo> result = new ArrayList<>();
  491. for (SearchHit hit : response.getHits()) {
  492. UserInfo userInfo = JSON.parseObject(hit.getSourceAsString(), UserInfo.class);
  493. result.add(userInfo);
  494. }
  495. log.info("获取查询结果:" + result);
  496. return result;
  497. }
  498. }
  499. return null;
  500. }
  501. /**
  502. * 通配符查询( *:表示多个字符(0个或多个字符) ?:表示单个字符)
  503. *
  504. * @return 查询结果
  505. */
  506. @Override
  507. public List<UserInfo> wildcardQuery() {
  508. // 创建查询条件
  509. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  510. searchSourceBuilder.query(QueryBuilders.wildcardQuery(TEST_ES_DOCUMENT_QUERY_KEY + ".keyword", "*街区"));
  511. // 创建请求
  512. EsDocument annotation = UserInfo.class.getAnnotation(EsDocument.class);
  513. SearchRequest request = new SearchRequest(annotation.index());
  514. request.source(searchSourceBuilder);
  515. // 处理请求
  516. SearchResponse response = null;
  517. try {
  518. response = restHighLevelClient.search(request);
  519. log.info("通配符查询的响应体:" + response);
  520. } catch (IOException e) {
  521. e.printStackTrace();
  522. }
  523. // 处理响应
  524. if (response != null) {
  525. if (RestStatus.OK.equals(response.status()) && response.getHits().totalHits > 0) {
  526. List<UserInfo> result = new ArrayList<>();
  527. for (SearchHit hit : response.getHits()) {
  528. UserInfo userInfo = JSON.parseObject(hit.getSourceAsString(), UserInfo.class);
  529. result.add(userInfo);
  530. }
  531. log.info("获取查询结果:" + result);
  532. return result;
  533. }
  534. }
  535. return null;
  536. }
  537. /**
  538. * 布尔查询(重点!)
  539. *
  540. * @return 查询结果
  541. */
  542. @Override
  543. public List<UserInfo> boolQuery() {
  544. // 创建bool查询构建器
  545. BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
  546. // 创建查询条件(若有多个条件,就让后面接着加)
  547. boolQueryBuilder.must(QueryBuilders.termsQuery(TEST_ES_DOCUMENT_QUERY_KEY + ".keyword", "用户2住在2号街区", "用户3住在3号街区", "用户8住在8号街区"))
  548. .filter().add(QueryBuilders.rangeQuery("birthday").format("yyyy").gte("1990").lte("1995").includeLower(true).includeUpper(true));
  549. // 创建查询源并将构建器配置其中
  550. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  551. searchSourceBuilder.query(boolQueryBuilder);
  552. // 创建请求
  553. EsDocument annotation = UserInfo.class.getAnnotation(EsDocument.class);
  554. SearchRequest request = new SearchRequest(annotation.index());
  555. request.source(searchSourceBuilder);
  556. // 处理请求
  557. SearchResponse response = null;
  558. try {
  559. response = restHighLevelClient.search(request);
  560. log.info("布尔查询的响应体:" + response);
  561. } catch (IOException e) {
  562. e.printStackTrace();
  563. }
  564. // 处理响应
  565. if (response != null) {
  566. if (RestStatus.OK.equals(response.status()) && response.getHits().totalHits > 0) {
  567. List<UserInfo> result = new ArrayList<>();
  568. for (SearchHit hit : response.getHits()) {
  569. UserInfo userInfo = JSON.parseObject(hit.getSourceAsString(), UserInfo.class);
  570. result.add(userInfo);
  571. }
  572. log.info("获取查询结果:" + result);
  573. return result;
  574. }
  575. }
  576. return null;
  577. }
  578. /**
  579. * 聚合统计查询(重点!)
  580. *
  581. * @return 查询结果如下:
  582. * {
  583. * "salary_stats": {
  584. * "name": "salary_stats",
  585. * "count": 26,
  586. * "min": 100.0,
  587. * "max": 1100.0,
  588. * "sum": 12100.0,
  589. * "avg": 465.38461538461536,
  590. * "type": "stats",
  591. * "sumAsString": "12100.0",
  592. * "maxAsString": "1100.0",
  593. * "avgAsString": "465.38461538461536",
  594. * "minAsString": "100.0",
  595. * "metaData": null,
  596. * "fragment": true
  597. * }
  598. * }
  599. */
  600. @Override
  601. public Object aggregationStats() {
  602. /*
  603. 声明聚合的类型与字段
  604. 统计数据(可拿到总数、平均数、最大值、最小值等数据) -- stats("字段_stats").field("字段")
  605. 总数 -- count("字段_count").field("字段")
  606. 平均数 -- avg("字段_avg").field("字段")
  607. 以此类推...
  608. */
  609. AggregationBuilder aggr = AggregationBuilders.stats("salary_stats").field("salary");
  610. // 设置查询条件
  611. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  612. searchSourceBuilder.aggregation(aggr);
  613. // 设置查询结果不返回,只返回聚合的结果
  614. searchSourceBuilder.size(0);
  615. // 创建请求
  616. EsDocument annotation = UserInfo.class.getAnnotation(EsDocument.class);
  617. SearchRequest request = new SearchRequest(annotation.index());
  618. request.source(searchSourceBuilder);
  619. // 处理请求
  620. SearchResponse response = null;
  621. try {
  622. response = restHighLevelClient.search(request);
  623. log.info("聚合统计查询的响应体:" + response);
  624. } catch (IOException e) {
  625. e.printStackTrace();
  626. }
  627. // 处理响应
  628. if (response != null) {
  629. // 获取响应中的聚合信息
  630. Aggregations aggregations = response.getAggregations();
  631. if (RestStatus.OK.equals(response.status()) && aggregations != null) {
  632. /*
  633. 解析数据类型
  634. ParsedStats -- 聚合信息
  635. ParsedValueCount -- 总数
  636. ParsedAvg -- 平均数
  637. 以此类推
  638. */
  639. ParsedStats stats = aggregations.get("salary_stats");
  640. log.info("-------------------------------------------");
  641. log.info("聚合信息:");
  642. log.info("count:{}", stats.getCount());
  643. log.info("avg:{}", stats.getAvg());
  644. log.info("max:{}", stats.getMax());
  645. log.info("min:{}", stats.getMin());
  646. log.info("sum:{}", stats.getSum());
  647. log.info("-------------------------------------------");
  648. return aggregations.getAsMap();
  649. }
  650. }
  651. return null;
  652. }
  653. /**
  654. * 聚合分桶查询(重点!)
  655. *
  656. * @return 查询结果: 桶名 与 对应的总数
  657. */
  658. @Override
  659. public Object aggregationBucket() {
  660. /*
  661. < 声明聚合的类型与字段 >
  662. 按岁数进行聚合分桶
  663. TermsAggregationBuilder aggr = AggregationBuilders.terms("age_bucket").field("age");
  664. 按工资范围进行聚合分桶
  665. AggregationBuilder aggr = AggregationBuilders.range("salary_range_bucket")
  666. .field("salary")
  667. .addUnboundedTo("低级员工", 3000)
  668. .addRange("中级员工", 5000, 9000)
  669. .addUnboundedFrom("高级员工", 9000);
  670. 按照时间范围进行分桶
  671. AggregationBuilder aggr = AggregationBuilders.dateRange("date_range_bucket")
  672. .field("birthday")
  673. .format("yyyy")
  674. .addRange("1985-1990", "1985", "1990")
  675. .addRange("1990-1995", "1990", "1995");
  676. 按工资多少进行聚合分桶
  677. AggregationBuilder aggr = AggregationBuilders.histogram("salary_histogram")
  678. .field("salary")
  679. .extendedBounds(0, 12000)
  680. .interval(3000);
  681. 按出生日期进行分桶
  682. AggregationBuilder aggr = AggregationBuilders.dateHistogram("birthday_histogram")
  683. .field("birthday")
  684. .interval(1)
  685. .dateHistogramInterval(DateHistogramInterval.YEAR)
  686. .format("yyyy");
  687. */
  688. TermsAggregationBuilder aggr = AggregationBuilders.terms("age_bucket").field("age");
  689. // 创建查询条件
  690. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  691. searchSourceBuilder.aggregation(aggr);
  692. searchSourceBuilder.size(10);
  693. // 创建请求
  694. EsDocument annotation = UserInfo.class.getAnnotation(EsDocument.class);
  695. SearchRequest request = new SearchRequest(annotation.index());
  696. request.source(searchSourceBuilder);
  697. // 处理请求
  698. SearchResponse response = null;
  699. try {
  700. response = restHighLevelClient.search(request);
  701. log.info("聚合分桶查询的响应体:" + response);
  702. } catch (IOException e) {
  703. e.printStackTrace();
  704. }
  705. // 处理响应
  706. if (response != null) {
  707. if (RestStatus.OK.equals(response.status())) {
  708. // 获取响应中的聚合信息
  709. Aggregations aggregations = response.getAggregations();
  710. // 分桶
  711. Terms byCompanyAggregation = aggregations.get("age_bucket"); // 不同的聚合类型修改 声明聚合的类型与字段 中AggregationBuilders的不同名称即可
  712. List<? extends Terms.Bucket> buckets = byCompanyAggregation.getBuckets();
  713. // 输出各个桶的内容
  714. log.info("-------------------------------------------");
  715. log.info("聚合信息:");
  716. for (Terms.Bucket bucket : buckets) {
  717. log.info("桶名:{} | 总数:{}", bucket.getKeyAsString(), bucket.getDocCount());
  718. }
  719. log.info("-------------------------------------------");
  720. return aggregations.getAsMap();
  721. }
  722. }
  723. return null;
  724. }
  725. /**
  726. * 聚合查询场景分析
  727. * (按岁数分桶、然后统计各个岁数收入最高的用户信息)
  728. *
  729. * @return 查询结果:
  730. * 桶名:1
  731. * 值:{"address":"湖南省常德市","age":1,"birthday":"1991-01-01","createTime":1631498892472,"name":"用户1","remark":"这是第1条文档信息的批量插入","salary":200}
  732. *
  733. * 以此类推...
  734. */
  735. @Override
  736. public Object aggregationAnalysis() {
  737. // 构建聚合参数
  738. AggregationBuilder testTop = AggregationBuilders.topHits("salary_max_user")
  739. .size(1)
  740. .sort("salary", SortOrder.DESC);
  741. AggregationBuilder salaryBucket = AggregationBuilders.terms("salary_bucket")
  742. .field("age")
  743. .size(10);
  744. salaryBucket.subAggregation(testTop);
  745. // 创建查询条件
  746. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  747. searchSourceBuilder.size(0);
  748. searchSourceBuilder.aggregation(salaryBucket);
  749. // 创建请求
  750. EsDocument annotation = UserInfo.class.getAnnotation(EsDocument.class);
  751. SearchRequest request = new SearchRequest(annotation.index());
  752. request.source(searchSourceBuilder);
  753. // 处理请求
  754. SearchResponse response = null;
  755. try {
  756. response = restHighLevelClient.search(request);
  757. log.info("聚合查询场景分析的响应体:" + response);
  758. } catch (IOException e) {
  759. e.printStackTrace();
  760. }
  761. // 处理响应
  762. if (response != null) {
  763. // 获取响应中的聚合信息
  764. Aggregations aggregations = response.getAggregations();
  765. if (RestStatus.OK.equals(response.status())) {
  766. // 分桶
  767. Terms byCompanyAggregation = aggregations.get("salary_bucket");
  768. List<? extends Terms.Bucket> buckets = byCompanyAggregation.getBuckets();
  769. // 输出各个桶的内容
  770. log.info("-------------------------------------------");
  771. log.info("聚合信息:");
  772. for (Terms.Bucket bucket : buckets) {
  773. log.info("桶名:{}", bucket.getKeyAsString());
  774. ParsedTopHits topHits = bucket.getAggregations().get("salary_max_user");
  775. for (SearchHit hit:topHits.getHits()){
  776. log.info(hit.getSourceAsString());
  777. }
  778. }
  779. log.info("-------------------------------------------");
  780. return aggregations.getAsMap();
  781. }
  782. }
  783. return response;
  784. }
  785. }

说明

        本文章是在学习了 <全栈开发者社区> 与 <狂神说> 的Es相关讲解后的实践与补充,想学习更加完整的知识可去膜拜大神!!

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/68395
推荐阅读
相关标签