介绍

Spirng Boot整合ElasticSearch,通过Java代码操作ElasticSearch。
https://www.elastic.co/guide/en/elasticsearch/client/index.html
image.png
Spring Boot集成ElasticSearch的时候,我们需要引入高阶客户端【elasticsearch-rest-high-level-client】【elasticsearch-rest-client】和【elasticsearch】来操作Elasticsearch,在引入依赖的时候,需要严格注意版本关系,否则在使用过程中会出很多问题。
另外,TransportClient 为代表的ES原生客户端,不能执行原生DSL语句,必须使用它的Java API方法。
最近elasticsearch官网,宣布计划在7.0以后的版本中废除TransportClient。以Java high Level Rest Client为主。
image.png

【客户端开发环境搭建】

1. 创建Maven工程

springboot-highlevel-client

2.pom文件导入依赖

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <modelVersion>4.0.0</modelVersion>
  6. <groupId>com.adong.elasticsearch</groupId>
  7. <artifactId>springboot-highlevel-client</artifactId>
  8. <version>1.0-SNAPSHOT</version>
  9. <parent>
  10. <groupId>org.springframework.boot</groupId>
  11. <artifactId>spring-boot-starter-parent</artifactId>
  12. <version>2.2.2.RELEASE</version>
  13. <relativePath/>
  14. </parent>
  15. <properties>
  16. <java.version>1.8</java.version>
  17. </properties>
  18. <dependencies>
  19. <!--elasticsearch的高级别rest客户端-->
  20. <dependency>
  21. <groupId>org.elasticsearch.client</groupId>
  22. <artifactId>elasticsearch-rest-high-level-client</artifactId>
  23. <version>6.8.1</version>
  24. </dependency>
  25. <!--elasticsearch的rest客户端-->
  26. <dependency>
  27. <groupId>org.elasticsearch.client</groupId>
  28. <artifactId>elasticsearch-rest-client</artifactId>
  29. <version>6.8.1</version>
  30. </dependency>
  31. <!--elasticsearch的核心jar包-->
  32. <dependency>
  33. <groupId>org.elasticsearch</groupId>
  34. <artifactId>elasticsearch</artifactId>
  35. <version>6.8.1</version>
  36. </dependency>
  37. <dependency>
  38. <groupId>org.springframework.boot</groupId>
  39. <artifactId>spring-boot-starter</artifactId>
  40. </dependency>
  41. <!--json转换的jar包-->
  42. <dependency>
  43. <groupId>com.fasterxml.jackson.core</groupId>
  44. <artifactId>jackson-databind</artifactId>
  45. <version>2.9.9</version>
  46. </dependency>
  47. <dependency>
  48. <groupId>org.springframework.boot</groupId>
  49. <artifactId>spring-boot-devtools</artifactId>
  50. <scope>runtime</scope>
  51. <optional>true</optional>
  52. </dependency>
  53. <dependency>
  54. <groupId>org.springframework.boot</groupId>
  55. <artifactId>spring-boot-configuration-processor</artifactId>
  56. <optional>true</optional>
  57. </dependency>
  58. <dependency>
  59. <groupId>org.projectlombok</groupId>
  60. <artifactId>lombok</artifactId>
  61. <optional>true</optional>
  62. </dependency>
  63. <dependency>
  64. <groupId>org.springframework.boot</groupId>
  65. <artifactId>spring-boot-starter-test</artifactId>
  66. <scope>test</scope>
  67. </dependency>
  68. </dependencies>
  69. <build>
  70. <plugins>
  71. <plugin>
  72. <groupId>org.springframework.boot</groupId>
  73. <artifactId>spring-boot-maven-plugin</artifactId>
  74. </plugin>
  75. </plugins>
  76. </build>
  77. </project>

3.配置文件

  1. elasticsearch:
  2. host: 127.0.0.1
  3. port: 9200
  4. logging:
  5. level:
  6. com.adong.es: debug

4.主启动类

  1. @SpringBootApplication
  2. public class ElasticSearchMainApplication {
  3. public static void main(String[] args) {
  4. SpringApplication.run(ElasticSearchMainApplication.class, args);
  5. }
  6. }

5.配置类

  1. package com.adong.es.config;
  2. import lombok.Data;
  3. import org.apache.http.HttpHost;
  4. import org.elasticsearch.client.RestClient;
  5. import org.elasticsearch.client.RestClientBuilder;
  6. import org.elasticsearch.client.RestHighLevelClient;
  7. import org.springframework.boot.context.properties.ConfigurationProperties;
  8. import org.springframework.context.annotation.Bean;
  9. import org.springframework.context.annotation.Configuration;
  10. import org.springframework.stereotype.Component;
  11. @Configuration
  12. @ConfigurationProperties(prefix = "elasticsearch") // 读取配置文件内容
  13. @Component
  14. @Data //安装Lombok插件
  15. public class ElasticSearchConfig {
  16. private String host;
  17. private Integer port;
  18. @Bean
  19. public RestHighLevelClient client() {
  20. RestClientBuilder builder = RestClient.builder(new HttpHost(host, port));
  21. RestHighLevelClient restHighLevelClient = new RestHighLevelClient(builder);
  22. return restHighLevelClient;
  23. }
  24. }

【索引库操作】

索引库操作
目标:使用ElasticSearch的高阶客户端,编写Java代码,操作索引库
分析:Java high level客户端的操作,是通过发送RESTful接口调用的方式处理请求。

  1. package com.adong.es.test;
  2. import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
  3. import org.elasticsearch.action.support.master.AcknowledgedResponse;
  4. import org.elasticsearch.client.RequestOptions;
  5. import org.elasticsearch.client.RestHighLevelClient;
  6. import org.elasticsearch.client.indices.CreateIndexRequest;
  7. import org.elasticsearch.client.indices.CreateIndexResponse;
  8. import org.elasticsearch.client.indices.GetIndexRequest;
  9. import org.elasticsearch.client.indices.GetIndexResponse;
  10. import org.junit.Test;
  11. import org.junit.runner.RunWith;
  12. import org.springframework.boot.test.context.SpringBootTest;
  13. import org.springframework.test.context.junit4.SpringRunner;
  14. import javax.annotation.Resource;
  15. import java.io.IOException;
  16. @RunWith(SpringRunner.class)
  17. @SpringBootTest
  18. public class IndexTest {
  19. //@Autowired
  20. @Resource
  21. private RestHighLevelClient client;
  22. /**
  23. * 目标:创建索引库
  24. * 1.创建请求对象 设置索引库name
  25. * 2.客户端发送请求,获取响应对象
  26. * 3.打印响应对象中的返回结果
  27. * 4.关闭客户端,释放连接资源
  28. */
  29. @Test
  30. public void create() throws IOException {
  31. //1.创建请求对象,创建索引的请求
  32. CreateIndexRequest request = new CreateIndexRequest("shopping");
  33. //2.客户端发送请求,获取响应对象
  34. CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
  35. //3.打印响应对象中的返回结果
  36. //返回index信息
  37. System.out.println("index:" + response.index());
  38. //acknowledged代表创建成功
  39. System.out.println("acknowledged:" + response.isAcknowledged());
  40. //4.关闭客户端,释放连接资源
  41. client.close();
  42. }
  43. //查看索引库
  44. @Test
  45. public void getIndex() throws IOException {
  46. //1.创建请求对象:查询索引库
  47. GetIndexRequest request = new GetIndexRequest("shopping");
  48. //2.客户端执行请求发送,返回响应对象
  49. GetIndexResponse response = client.indices().get(request, RequestOptions.DEFAULT);
  50. //3.打印结果信息
  51. System.out.println("aliases:" + response.getAliases());
  52. System.out.println("mappings:" + response.getMappings());
  53. System.out.println("settings:" + response.getSettings());
  54. //4.关闭客户端,释放连接资源
  55. client.close();
  56. }
  57. //删除索引库
  58. @Test
  59. public void deleteIndex() throws IOException {
  60. //1.创建请求对象
  61. DeleteIndexRequest request = new DeleteIndexRequest("shopping");
  62. //2.客户端发送请求,获取响应对象
  63. AcknowledgedResponse response = client.indices().delete(request, RequestOptions.DEFAULT);
  64. //3.打印结果信息
  65. System.out.println("ack:" + response.isAcknowledged());
  66. //4.关闭客户端,释放连接资源
  67. client.close();
  68. }
  69. }

【配置映射】

RestHighLevelClient配置映射,与kibana略有区别。在客户端中配置映射,不支持设置类型type。不设置type,并不代表没有,而是默认的type为_doc
映射操作:
1.配置映射,一共2种方式:
第一种:使用XContentBuilder,构建请求体
第二种:使用JSON字符串
2.查看映射配置

  1. package com.adong.es.test;
  2. import org.elasticsearch.action.support.master.AcknowledgedResponse;
  3. import org.elasticsearch.client.RequestOptions;
  4. import org.elasticsearch.client.RestHighLevelClient;
  5. import org.elasticsearch.client.indices.GetMappingsRequest;
  6. import org.elasticsearch.client.indices.GetMappingsResponse;
  7. import org.elasticsearch.client.indices.PutMappingRequest;
  8. import org.elasticsearch.common.xcontent.XContentBuilder;
  9. import org.elasticsearch.common.xcontent.XContentFactory;
  10. import org.elasticsearch.common.xcontent.XContentType;
  11. import org.junit.Test;
  12. import org.junit.runner.RunWith;
  13. import org.springframework.boot.test.context.SpringBootTest;
  14. import org.springframework.test.context.junit4.SpringRunner;
  15. import javax.annotation.Resource;
  16. import java.io.IOException;
  17. @RunWith(SpringRunner.class)
  18. @SpringBootTest
  19. public class MappingTest {
  20. @Resource
  21. private RestHighLevelClient client;
  22. /**
  23. * 目标:配置映射。第一种方式,使用XContentBuilder,构建请求体
  24. * 1.创建请求对象:配置映射
  25. * 设置索引库name
  26. * 设置配置映射请求体
  27. * 2.客户端发送请求,获取响应对象
  28. * 3.打印响应结果
  29. */
  30. @Test
  31. public void putMapping01() throws IOException {
  32. //1.创建请求对象:配置映射
  33. PutMappingRequest request = new PutMappingRequest("shopping01");
  34. //构建请求体
  35. XContentBuilder jsonBuilder = XContentFactory.jsonBuilder();
  36. jsonBuilder
  37. .startObject()
  38. .startObject("properties")
  39. .startObject("title")
  40. .field("type", "text")
  41. .field("analyzer", "ik_max_word")
  42. .endObject()
  43. .startObject("subtitle")
  44. .field("type", "text")
  45. .field("analyzer", "ik_max_word")
  46. .endObject()
  47. .startObject("images")
  48. .field("type", "keyword")
  49. .field("index", false)
  50. .endObject()
  51. .startObject("price")
  52. .field("type", "float")
  53. .endObject()
  54. .endObject()
  55. .endObject();
  56. //设置请求体,source("请求体json构建器对象");
  57. request.source(jsonBuilder);
  58. //2.客户端发送请求,获取响应对象
  59. AcknowledgedResponse response = client.indices().putMapping(request, RequestOptions.DEFAULT);
  60. //3.打印响应结果
  61. System.out.println("acknowledged::" + response.isAcknowledged());
  62. }
  63. /**
  64. * 目标:配置映射。第二种方式,使用JSON字符串
  65. * 1.创建请求对象:配置映射
  66. * 设置索引库name
  67. * 设置配置映射请求体
  68. * 2.客户端发送请求,获取响应对象
  69. * 3.打印响应结果
  70. */
  71. @Test
  72. public void putMapping02() throws IOException {
  73. //1.创建请求对象:配置映射
  74. PutMappingRequest request = new PutMappingRequest("shopping02");
  75. //设置请求体,source("请求体json字符串","请求体的数据类型");
  76. String s = "{\"properties\":{\"title\":{\"type\":\"text\",\"analyzer\":\"ik_max_word\"},\"subtitle\":{\"type\":\"text\",\"analyzer\":\"ik_max_word\"},\"price\":{\"type\":\"float\"},\"images\":{\"type\":\"keyword\",\"index\":false}}}";
  77. request.source(s, XContentType.JSON);
  78. //2.客户端发送请求,获取响应对象
  79. AcknowledgedResponse response = client.indices().putMapping(request, RequestOptions.DEFAULT);
  80. //3.打印响应结果
  81. System.out.println("acknowledged::" + response.isAcknowledged());
  82. }
  83. /**
  84. * 查看映射
  85. * 1.创建请求对象:查看映射
  86. * 设置索引库name
  87. * 2.客户端发送请求,获取响应对象
  88. * 3.打印响应结果
  89. */
  90. @Test
  91. public void getMapping() throws IOException {
  92. //1.创建请求对象:查看映射
  93. GetMappingsRequest request = new GetMappingsRequest();
  94. //设置索引库name
  95. request.indices("shopping01");
  96. //2.客户端发送请求,获取响应对象
  97. GetMappingsResponse response = client.indices().getMapping(request, RequestOptions.DEFAULT);
  98. //3.打印响应结果
  99. System.out.println("mappings::" + response.mappings());
  100. System.out.println("Source::" + response.mappings().get("shopping01").getSourceAsMap());
  101. }
  102. }

【文档操作】

创建Bean对象 :

  1. package com.adong.es.entities;
  2. import lombok.*;
  3. @Data
  4. @NoArgsConstructor
  5. @AllArgsConstructor
  6. @ToString
  7. @Builder
  8. public class Product {
  9. private Long id;//商品唯一标识
  10. private String title;//商品名称
  11. private Double price;//商品价格
  12. private String images;//图片地址
  13. }

测试类 :

  1. package com.adong.es.test;
  2. import com.adong.es.entities.Product;
  3. import com.fasterxml.jackson.databind.ObjectMapper;
  4. import org.elasticsearch.action.bulk.BulkRequest;
  5. import org.elasticsearch.action.bulk.BulkResponse;
  6. import org.elasticsearch.action.delete.DeleteRequest;
  7. import org.elasticsearch.action.delete.DeleteResponse;
  8. import org.elasticsearch.action.get.GetRequest;
  9. import org.elasticsearch.action.get.GetResponse;
  10. import org.elasticsearch.action.index.IndexRequest;
  11. import org.elasticsearch.action.index.IndexResponse;
  12. import org.elasticsearch.action.update.UpdateRequest;
  13. import org.elasticsearch.action.update.UpdateResponse;
  14. import org.elasticsearch.client.RequestOptions;
  15. import org.elasticsearch.client.RestHighLevelClient;
  16. import org.elasticsearch.common.xcontent.XContentType;
  17. import org.junit.Test;
  18. import org.junit.runner.RunWith;
  19. import org.springframework.boot.test.context.SpringBootTest;
  20. import org.springframework.test.context.junit4.SpringRunner;
  21. import javax.annotation.Resource;
  22. import java.io.IOException;
  23. /**
  24. * 目标:文档的操作
  25. * 1.新增文档
  26. * 2.修改
  27. * 3.根据id查询文档
  28. * 4.删除
  29. * 5.批量
  30. */
  31. @RunWith(SpringRunner.class)
  32. @SpringBootTest
  33. public class DocumentTest {
  34. @Resource
  35. private RestHighLevelClient client;
  36. //新增文档
  37. @Test
  38. public void saveDoc() throws IOException {
  39. //1.创建请求对象(创建索引库CreateIndexRequest),索引库名称、类型名称、主键id
  40. IndexRequest request = new IndexRequest().index("shopping01").type("_doc").id("2");
  41. //方式1:写一个Product对象将对象转为json字符串
  42. Product product = Product.builder().id(1L).title("小米手机").price(1999.0).build();
  43. ObjectMapper objectMapper = new ObjectMapper();
  44. String productJson = objectMapper.writeValueAsString(product);
  45. request.source(productJson, XContentType.JSON);
  46. //方式2:直接在source中写入key-value参数
  47. //request.source(XContentType.JSON, "id", 2L,"title", "小米手机", "price", "3999");
  48. //2.客户端发送请求,获取响应对象
  49. IndexResponse response = client.index(request, RequestOptions.DEFAULT);
  50. //3.打印结果信息
  51. System.out.println("_index:" + response.getIndex());
  52. System.out.println("_type:" + response.getType());
  53. System.out.println("_id:" + response.getId());
  54. System.out.println("_result:" + response.getResult());
  55. }
  56. //修改文档,不是覆盖修改
  57. @Test
  58. public void update() throws IOException {
  59. //1.创建请求对象(创建索引库CreateIndexRequest),索引库名称、类型名称、主键id
  60. UpdateRequest request = new UpdateRequest().index("shopping01").type("_doc").id("2");
  61. //设置请求体
  62. request.doc(XContentType.JSON, "id", "2", "title", "小米手机", "price", "2999");
  63. //2.客户端发送请求,获取响应对象
  64. UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
  65. ////3.打印结果信息
  66. System.out.println("_index:" + response.getIndex());
  67. System.out.println("_type:" + response.getType());
  68. System.out.println("_id:" + response.getId());
  69. System.out.println("_result:" + response.getResult());
  70. }
  71. //查询文档
  72. @Test
  73. public void getDoc() throws IOException {
  74. //1.创建请求对象
  75. GetRequest request = new GetRequest().index("shopping01").type("_doc").id("2");
  76. //2.客户端发送请求,获取响应对象
  77. GetResponse response = client.get(request, RequestOptions.DEFAULT);
  78. ////3.打印结果信息
  79. System.out.println("_index:" + response.getIndex());
  80. System.out.println("_type:" + response.getType());
  81. System.out.println("_id:" + response.getId());
  82. System.out.println("source:" + response.getSourceAsString());
  83. }
  84. //删除文档
  85. @Test
  86. public void deleteDoc() throws IOException {
  87. //创建请求对象
  88. DeleteRequest request = new DeleteRequest().index("shopping01").type("_doc").id("1");
  89. //客户端发送请求,获取响应对象
  90. DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);
  91. //打印信息
  92. System.out.println(response.toString());
  93. }
  94. //批量新增操作
  95. @Test
  96. public void bulkSave() throws IOException {
  97. //创建请求对象
  98. BulkRequest request = new BulkRequest();
  99. request.add(new IndexRequest().index("shopping01").type("_doc").id("1").source(XContentType.JSON, "title", "小米手机"));
  100. request.add(new IndexRequest().index("shopping01").type("_doc").id("2").source(XContentType.JSON, "title", "苹果手机"));
  101. request.add(new IndexRequest().index("shopping01").type("_doc").id("3").source(XContentType.JSON, "title", "华为手机"));
  102. //客户端发送请求,获取响应对象
  103. BulkResponse responses = client.bulk(request, RequestOptions.DEFAULT);
  104. //打印结果信息
  105. System.out.println("took:" + responses.getTook());
  106. System.out.println("items:" + responses.getItems());
  107. }
  108. //批量删除操作
  109. @Test
  110. public void bulkDelete() throws IOException {
  111. //创建请求对象
  112. BulkRequest request = new BulkRequest();
  113. request.add(new DeleteRequest().index("shopping01").type("_doc").id("1"));
  114. request.add(new DeleteRequest().index("shopping01").type("_doc").id("2"));
  115. request.add(new DeleteRequest().index("shopping01").type("_doc").id("3"));
  116. //客户端发送请求,获取响应对象
  117. BulkResponse responses = client.bulk(request, RequestOptions.DEFAULT);
  118. //打印结果信息
  119. System.out.println("took:" + responses.getTook());
  120. System.out.println("items:" + responses.getItems());
  121. }
  122. }

【请求体查询】

  1. package com.adong.es.test;
  2. import org.elasticsearch.action.bulk.BulkRequest;
  3. import org.elasticsearch.action.bulk.BulkResponse;
  4. import org.elasticsearch.action.index.IndexRequest;
  5. import org.elasticsearch.action.search.SearchRequest;
  6. import org.elasticsearch.action.search.SearchResponse;
  7. import org.elasticsearch.client.RequestOptions;
  8. import org.elasticsearch.client.RestHighLevelClient;
  9. import org.elasticsearch.common.unit.Fuzziness;
  10. import org.elasticsearch.common.xcontent.XContentType;
  11. import org.elasticsearch.index.query.BoolQueryBuilder;
  12. import org.elasticsearch.index.query.QueryBuilders;
  13. import org.elasticsearch.search.SearchHit;
  14. import org.elasticsearch.search.SearchHits;
  15. import org.elasticsearch.search.builder.SearchSourceBuilder;
  16. import org.elasticsearch.search.sort.SortOrder;
  17. import org.junit.Test;
  18. import org.junit.runner.RunWith;
  19. import org.springframework.boot.test.context.SpringBootTest;
  20. import org.springframework.test.context.junit4.SpringRunner;
  21. import javax.annotation.Resource;
  22. import java.io.IOException;
  23. @RunWith(SpringRunner.class)
  24. @SpringBootTest
  25. public class RequestBodyTest {
  26. @Resource
  27. private RestHighLevelClient client;
  28. /**
  29. * 初始化查询数据
  30. */
  31. @Test
  32. public void initData() throws IOException {
  33. //批量新增操作
  34. BulkRequest request = new BulkRequest();
  35. request.add(new IndexRequest().type("_doc").index("shopping01").source(XContentType.JSON, "title", "小米手机", "images", "http://www.gulixueyuan.com/xm.jpg", "price", 1999.0));
  36. request.add(new IndexRequest().type("_doc").index("shopping01").source(XContentType.JSON, "title", "小米电视", "images", "http://www.gulixueyuan.com/xmds.jpg", "price", 2999.0));
  37. request.add(new IndexRequest().type("_doc").index("shopping01").source(XContentType.JSON, "title", "华为手机", "images", "http://www.gulixueyuan.com/hw.jpg", "price", 4999.0, "subtitle", "小米"));
  38. request.add(new IndexRequest().type("_doc").index("shopping01").source(XContentType.JSON, "title", "apple手机", "images", "http://www.gulixueyuan.com/appletl.jpg", "price", 5999.00));
  39. request.add(new IndexRequest().type("_doc").index("shopping01").source(XContentType.JSON, "title", "apple", "images", "http://www.gulixueyuan.com/apple.jpg", "price", 3999.00));
  40. BulkResponse response = client.bulk(request, RequestOptions.DEFAULT);
  41. System.out.println("took::" + response.getTook());
  42. System.out.println("Items::" + response.getItems());
  43. }
  44. //请求体查询-基本查询
  45. //1.创建请求对象
  46. //2.客户端发送请求,获取响应对象
  47. //3.打印结果信息
  48. @Test
  49. public void basicQuery() throws IOException {
  50. //1.创建请求对象
  51. SearchRequest request = new SearchRequest().indices("shopping01").types("_doc");
  52. //构建查询的请求体
  53. SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
  54. //查询所有
  55. //sourceBuilder.query(QueryBuilders.matchAllQuery());//
  56. //match查询,带分词器的查询
  57. //sourceBuilder.query(QueryBuilders.matchQuery("title","小米手机").operator(Operator.AND));
  58. //term查询:不带分词器,查询条件作为关键词
  59. sourceBuilder.query(QueryBuilders.termQuery("price", "1999"));
  60. //TODO ...multi_match:多个字段的match查询
  61. //TODO ...terms查询:多个关键词去匹配
  62. request.source(sourceBuilder);
  63. //2.客户端发送请求,获取响应对象
  64. SearchResponse response = client.search(request, RequestOptions.DEFAULT);
  65. //3.打印结果信息
  66. printResult(response);
  67. }
  68. /**
  69. * 打印结果信息
  70. */
  71. private void printResult(SearchResponse response) {
  72. SearchHits hits = response.getHits();
  73. System.out.println("took:" + response.getTook());
  74. System.out.println("timeout:" + response.isTimedOut());
  75. System.out.println("total:" + hits.getTotalHits());
  76. System.out.println("MaxScore:" + hits.getMaxScore());
  77. System.out.println("hits========>>");
  78. for (SearchHit hit : hits) {
  79. //输出每条查询的结果信息
  80. System.out.println(hit.getSourceAsString());
  81. }
  82. System.out.println("<<========");
  83. }
  84. /**
  85. * 目标:查询的字段过滤,分页,排序
  86. *
  87. * @throws IOException
  88. */
  89. @Test
  90. public void fetchSourceAndSortAndByPage() throws IOException {
  91. //1.创建请求对象
  92. SearchRequest request = new SearchRequest().indices("shopping01").types("_doc");
  93. //构建查询的请求体
  94. SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
  95. //查询所有
  96. sourceBuilder.query(QueryBuilders.matchAllQuery());
  97. //分页信息
  98. //当前页其实索引(第一条数据的顺序号),from
  99. sourceBuilder.from(2);
  100. //每页显示多少条size
  101. sourceBuilder.size(2);
  102. //排序信息,参数一:排序的字段,参数二:顺序ASC升序,降序DESC
  103. sourceBuilder.sort("price", SortOrder.ASC);
  104. //查询字段过滤
  105. String[] excludes = {};
  106. String[] includes = {"title", "subtitle", "price"};
  107. sourceBuilder.fetchSource(includes, excludes);
  108. request.source(sourceBuilder);
  109. //2.客户端发送请求,获取响应对象
  110. SearchResponse response = client.search(request, RequestOptions.DEFAULT);
  111. //3.打印结果信息
  112. printResult(response);
  113. }
  114. /**
  115. * 高级查询
  116. */
  117. @Test
  118. public void boolAndRangeAndFuzzyQuery() throws IOException {
  119. //1.创建请求对象
  120. SearchRequest request = new SearchRequest().indices("shopping01").types("_doc");
  121. //构建查询的请求体
  122. SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
  123. //高级查询的三种方式:
  124. //-----------------------------------------------------------------------------
  125. // //bool查询:查询title中必须包含小米,一定不含有电视,应该含有手机的所有商品
  126. BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
  127. // //must
  128. // boolQueryBuilder.must(QueryBuilders.matchQuery("title", "小米"));
  129. // //must not
  130. // boolQueryBuilder.mustNot(QueryBuilders.matchQuery("title", "电视"));
  131. // //should
  132. // boolQueryBuilder.should(QueryBuilders.matchQuery("title", "手机"));
  133. // sourceBuilder.query(boolQueryBuilder);
  134. //-----------------------------------------------------------------------------
  135. //范围查询:查询价格大于3千,小于5千的所有商品
  136. // RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("price");
  137. // //#### gt 大于(greater than)
  138. // rangeQuery.gt("3000");
  139. // //#### lt 小于(less than)
  140. // rangeQuery.lt("5000");
  141. // //#### gte 大于等于(greater than equals)
  142. // //#### lte 小于等于(less than equals)
  143. // sourceBuilder.query(rangeQuery);
  144. //-----------------------------------------------------------------------------
  145. //模糊查询:查询包含apple关键词的所有商品,完成模糊查询cpple
  146. sourceBuilder.query(QueryBuilders.fuzzyQuery("title", "cpple").fuzziness(Fuzziness.ONE));
  147. //-----------------------------------------------------------------------------
  148. request.source(sourceBuilder);
  149. //2.客户端发送请求,获取响应对象
  150. SearchResponse response = client.search(request, RequestOptions.DEFAULT);
  151. //3.打印结果信息
  152. printResult(response);
  153. }
  154. }

【高亮查询】

  1. package com.adong.es.test;
  2. import org.elasticsearch.action.search.SearchRequest;
  3. import org.elasticsearch.action.search.SearchResponse;
  4. import org.elasticsearch.client.RequestOptions;
  5. import org.elasticsearch.client.RestHighLevelClient;
  6. import org.elasticsearch.index.query.QueryBuilders;
  7. import org.elasticsearch.index.query.TermsQueryBuilder;
  8. import org.elasticsearch.search.SearchHit;
  9. import org.elasticsearch.search.SearchHits;
  10. import org.elasticsearch.search.builder.SearchSourceBuilder;
  11. import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
  12. import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
  13. import org.junit.Test;
  14. import org.junit.runner.RunWith;
  15. import org.springframework.boot.test.context.SpringBootTest;
  16. import org.springframework.test.context.junit4.SpringRunner;
  17. import javax.annotation.Resource;
  18. import java.io.IOException;
  19. import java.util.Map;
  20. @RunWith(SpringRunner.class)
  21. @SpringBootTest
  22. public class HighLightTest {
  23. @Resource
  24. private RestHighLevelClient client;
  25. /**
  26. * 高亮查询,对查询关键词进行高亮
  27. * 1.创建请求对象:高亮查询
  28. * 设置索引库name
  29. * 设置类型type
  30. * 2.创建查询请求体构建器
  31. * 设置请求体
  32. * 3.客户端发送请求,获取响应对象
  33. * 4.打印响应结果
  34. */
  35. @Test
  36. public void highLighterQuery() throws IOException {
  37. //1.创建请求对象
  38. SearchRequest request = new SearchRequest().types("_doc").indices("shopping01");
  39. //2.创建查询请求体构建器
  40. SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
  41. //构建查询方式:高亮查询
  42. TermsQueryBuilder termsQueryBuilder = QueryBuilders.termsQuery("title", "apple");
  43. //设置查询方式
  44. sourceBuilder.query(termsQueryBuilder);
  45. //构建高亮字段
  46. HighlightBuilder highlightBuilder = new HighlightBuilder();
  47. highlightBuilder.preTags("<font color='red'>");//设置标签前缀
  48. highlightBuilder.postTags("</font>");//设置标签后缀
  49. highlightBuilder.field("title");//设置高亮字段
  50. //设置高亮构建对象
  51. sourceBuilder.highlighter(highlightBuilder);
  52. //设置请求体
  53. request.source(sourceBuilder);
  54. //3.客户端发送请求,获取响应对象
  55. SearchResponse response = client.search(request, RequestOptions.DEFAULT);
  56. //4.打印响应结果
  57. SearchHits hits = response.getHits();
  58. System.out.println("took::" + response.getTook());
  59. System.out.println("time_out::" + response.isTimedOut());
  60. System.out.println("total::" + hits.getTotalHits());
  61. System.out.println("max_score::" + hits.getMaxScore());
  62. System.out.println("hits::::>>");
  63. for (SearchHit hit : hits) {
  64. String sourceAsString = hit.getSourceAsString();
  65. System.out.println(sourceAsString);
  66. //打印高亮结果
  67. Map<String, HighlightField> highlightFields = hit.getHighlightFields();
  68. System.out.println(highlightFields);
  69. }
  70. System.out.println("<<::::");
  71. }
  72. }