当前位置:   article > 正文

ElasticSearch全文搜索引擎之查询API操作详解_elasticsearch searchrequest

elasticsearch searchrequest

目录

一、简介

二、查询API详解

三、总结


一、简介

前面一篇文章已经总结一些索引和文档相关的操作API,本篇文章将介绍Java客户端中如何查询搜索引擎中的数据,同样查询API也是基于RestHighLevelClient实现。

二、查询API详解

es查询API使用大体步骤:

  1. 构造SearchRequest查询请求对象,支持设置超时时间等信息;创建SeachRequest,如果没有传参数,这将针对所有索引运行。如果传了有参数,则按参数所传值为索引,此处“student_info”为索引库名称,大多数搜索参数都添加到SearchSourceBuilder中,它为搜索请求body中的所有内容提供了setter;
  2. 构造QueryBuilder对象,常见的QueryBuilder有BoolQueryBuilder、MatchQueryBuilder、RangeQueryBuilder等;
  3. 构造SearchSourceBuilder对象,调用searchSourceBuilder.query(xxxQueryBuilder)方法; //设置查询,可以是任何类型的QueryBuilder。
  4. 调用searchRequest.source(searchSourceBuilder)方法; //将SearchSourceBuilder添加到SeachRequest。
  5. 执行查询请求,restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
  6. 获取响应结果并解析;

RestHighLevelClient查询ES中数据的API主要有:must、match_all、match、should、range、order等等。

search查询的主要参数是SearchRequest,我们的查询条件index、type、字段、字段值 都封装在SearchRequest中;

而index、type是直接封装在SearchRequest的对象中,查询的字段、字段值、查询方式则封装在SearchRequest中的对象属性SearchSourceBuilder中;

下面通过几个常见的查询示例说明如何通过RestHighLevelClient查询es索引中数据。

【a】match_all全部匹配搜索

  • QueryBuilders.matchAllQuery()
  1. /**
  2. * match_all全部匹配搜索: QueryBuilders.matchAllQuery()
  3. */
  4. @Test
  5. void matchAllSearch() throws IOException {
  6. SearchRequest searchRequest = new SearchRequest("student_info");
  7. //构建搜索条件
  8. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  9. //全部匹配查询
  10. MatchAllQueryBuilder matchAllQueryBuilder = QueryBuilders.matchAllQuery();
  11. searchSourceBuilder.query(matchAllQueryBuilder);
  12. //设置超时时间
  13. searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
  14. searchRequest.source(searchSourceBuilder);
  15. SearchResponse response = null;
  16. try {
  17. //执行查询请求,获取响应结果
  18. response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
  19. } catch (IOException e) {
  20. e.printStackTrace();
  21. }
  22. //循环遍历查询结果
  23. System.out.println(JSON.toJSONString(response.getHits()));
  24. for (SearchHit documentFields : response.getHits().getHits()) {
  25. System.out.println(documentFields.getSourceAsMap());
  26. }
  27. restHighLevelClient.close();
  28. }

控制台日志如下: 

  1. {"fragment":true,"hits":[{"fields":{},"fragment":false,"highlightFields":{},"id":"1","matchedQueries":[],"primaryTerm":0,"rawSortValues":[],"score":1.0,"seqNo":-2,"sortValues":[],"sourceAsMap":{"name":"张三","age":10},"sourceAsString":"{\"age\":10,\"name\":\"张三\"}","sourceRef":{"fragment":true},"type":"_doc","version":-1},{"fields":{},"fragment":false,"highlightFields":{},"id":"2","matchedQueries":[],"primaryTerm":0,"rawSortValues":[],"score":1.0,"seqNo":-2,"sortValues":[],"sourceAsMap":{"name":"李四","age":20},"sourceAsString":"{\"age\":20,\"name\":\"李四\"}","sourceRef":{"fragment":true},"type":"_doc","version":-1},{"fields":{},"fragment":false,"highlightFields":{},"id":"3","matchedQueries":[],"primaryTerm":0,"rawSortValues":[],"score":1.0,"seqNo":-2,"sortValues":[],"sourceAsMap":{"name":"王五","age":30},"sourceAsString":"{\"age\":30,\"name\":\"王五\"}","sourceRef":{"fragment":true},"type":"_doc","version":-1},{"fields":{},"fragment":false,"highlightFields":{},"id":"4","matchedQueries":[],"primaryTerm":0,"rawSortValues":[],"score":1.0,"seqNo":-2,"sortValues":[],"sourceAsMap":{"name":"赵六","age":40},"sourceAsString":"{\"age\":40,\"name\":\"赵六\"}","sourceRef":{"fragment":true},"type":"_doc","version":-1},{"fields":{},"fragment":false,"highlightFields":{},"id":"5","matchedQueries":[],"primaryTerm":0,"rawSortValues":[],"score":1.0,"seqNo":-2,"sortValues":[],"sourceAsMap":{"name":"田七","age":50},"sourceAsString":"{\"age\":50,\"name\":\"田七\"}","sourceRef":{"fragment":true},"type":"_doc","version":-1}],"maxScore":1.0,"totalHits":{"relation":"EQUAL_TO","value":5}}
  2. {name=张三, age=10}
  3. {name=李四, age=20}
  4. {name=王五, age=30}
  5. {name=赵六, age=40}
  6. {name=田七, age=50}

【b】只返回特定字段

  • searchSourceBuilder.fetchSource("name", "age")

通常使用下面两种方法(任意一种)设置查询返回的字段集合,方法还接受一个或多个通配符模式的数组,以控制以更精细的方式包含或排除哪些字段。第一个是获取的字段,第二个是过滤的字段,默认获取全部。

  1. public SearchSourceBuilder fetchSource(@Nullable String include, @Nullable String exclude) {
  2. return this.fetchSource(include == null ? Strings.EMPTY_ARRAY : new String[]{include}, exclude == null ? Strings.EMPTY_ARRAY : new String[]{exclude});
  3. }
  4. public SearchSourceBuilder fetchSource(@Nullable String[] includes, @Nullable String[] excludes) {
  5. FetchSourceContext fetchSourceContext = this.fetchSourceContext != null ? this.fetchSourceContext : FetchSourceContext.FETCH_SOURCE;
  6. this.fetchSourceContext = new FetchSourceContext(fetchSourceContext.fetchSource(), includes, excludes);
  7. return this;
  8. }
  1. /**
  2. * 只返回特定字段: searchSourceBuilder.fetchSource("name", "age")
  3. */
  4. @Test
  5. void notAllFieldsSearch() throws IOException {
  6. SearchRequest searchRequest = new SearchRequest("student_info");
  7. //构建搜索条件
  8. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  9. //全部匹配查询
  10. MatchAllQueryBuilder matchAllQueryBuilder = QueryBuilders.matchAllQuery();
  11. searchSourceBuilder.query(matchAllQueryBuilder);
  12. //设置超时时间
  13. searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
  14. //只返回name字段,排除age字段
  15. searchSourceBuilder.fetchSource("name", "age");
  16. searchRequest.source(searchSourceBuilder);
  17. SearchResponse response = null;
  18. try {
  19. //执行查询请求,获取响应结果
  20. response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
  21. } catch (IOException e) {
  22. e.printStackTrace();
  23. }
  24. //循环遍历查询结果
  25. System.out.println(JSON.toJSONString(response.getHits()));
  26. for (SearchHit documentFields : response.getHits().getHits()) {
  27. System.out.println(documentFields.getSourceAsMap());
  28. }
  29. restHighLevelClient.close();
  30. }

控制台日志如下:

  1. {"fragment":true,"hits":[{"fields":{},"fragment":false,"highlightFields":{},"id":"1","matchedQueries":[],"primaryTerm":0,"rawSortValues":[],"score":1.0,"seqNo":-2,"sortValues":[],"sourceAsMap":{"name":"张三"},"sourceAsString":"{\"name\":\"张三\"}","sourceRef":{"fragment":true},"type":"_doc","version":-1},{"fields":{},"fragment":false,"highlightFields":{},"id":"2","matchedQueries":[],"primaryTerm":0,"rawSortValues":[],"score":1.0,"seqNo":-2,"sortValues":[],"sourceAsMap":{"name":"李四"},"sourceAsString":"{\"name\":\"李四\"}","sourceRef":{"fragment":true},"type":"_doc","version":-1},{"fields":{},"fragment":false,"highlightFields":{},"id":"3","matchedQueries":[],"primaryTerm":0,"rawSortValues":[],"score":1.0,"seqNo":-2,"sortValues":[],"sourceAsMap":{"name":"王五"},"sourceAsString":"{\"name\":\"王五\"}","sourceRef":{"fragment":true},"type":"_doc","version":-1},{"fields":{},"fragment":false,"highlightFields":{},"id":"4","matchedQueries":[],"primaryTerm":0,"rawSortValues":[],"score":1.0,"seqNo":-2,"sortValues":[],"sourceAsMap":{"name":"赵六"},"sourceAsString":"{\"name\":\"赵六\"}","sourceRef":{"fragment":true},"type":"_doc","version":-1},{"fields":{},"fragment":false,"highlightFields":{},"id":"5","matchedQueries":[],"primaryTerm":0,"rawSortValues":[],"score":1.0,"seqNo":-2,"sortValues":[],"sourceAsMap":{"name":"田七"},"sourceAsString":"{\"name\":\"田七\"}","sourceRef":{"fragment":true},"type":"_doc","version":-1}],"maxScore":1.0,"totalHits":{"relation":"EQUAL_TO","value":5}}
  2. {name=张三}
  3. {name=李四}
  4. {name=王五}
  5. {name=赵六}
  6. {name=田七}

【c】match模糊搜索

  • QueryBuilders.matchQuery("name", "张")
  1. /**
  2. * match模糊搜索: QueryBuilders.matchQuery("name", "张")
  3. * 查询name字段中包含"张"的记录
  4. */
  5. @Test
  6. void matchSearch() throws IOException {
  7. SearchRequest searchRequest = new SearchRequest("student_info");
  8. //构建搜索条件
  9. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  10. //查询name字段中包含"张"的记录
  11. MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("name", "张");
  12. searchSourceBuilder.query(matchQueryBuilder);
  13. //设置超时时间
  14. searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
  15. searchRequest.source(searchSourceBuilder);
  16. SearchResponse response = null;
  17. try {
  18. //执行查询请求,获取响应结果
  19. response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
  20. } catch (IOException e) {
  21. e.printStackTrace();
  22. }
  23. //循环遍历查询结果
  24. System.out.println(JSON.toJSONString(response.getHits()));
  25. for (SearchHit documentFields : response.getHits().getHits()) {
  26. System.out.println(documentFields.getSourceAsMap());
  27. }
  28. restHighLevelClient.close();
  29. }

控制台日志如下:

  1. {"fragment":true,"hits":[{"fields":{},"fragment":false,"highlightFields":{},"id":"1","matchedQueries":[],"primaryTerm":0,"rawSortValues":[],"score":1.3862942,"seqNo":-2,"sortValues":[],"sourceAsMap":{"name":"张三","age":10},"sourceAsString":"{\"age\":10,\"name\":\"张三\"}","sourceRef":{"fragment":true},"type":"_doc","version":-1}],"maxScore":1.3862942,"totalHits":{"relation":"EQUAL_TO","value":1}}
  2. {name=张三, age=10}

【d】term精确搜索

  • QueryBuilders.termQuery("name", "张")
  1. /**
  2. * term精确搜索
  3. */
  4. @Test
  5. void termSearch() throws IOException {
  6. SearchRequest searchRequest = new SearchRequest("student_info");
  7. //构建搜索条件
  8. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  9. //精确查询 name精确匹配"张"的记录
  10. TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "张");
  11. searchSourceBuilder.query(termQueryBuilder);
  12. //设置超时时间
  13. searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
  14. searchRequest.source(searchSourceBuilder);
  15. SearchResponse response = null;
  16. try {
  17. //执行查询请求,获取响应结果
  18. response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
  19. } catch (IOException e) {
  20. e.printStackTrace();
  21. }
  22. //循环遍历查询结果
  23. System.out.println(JSON.toJSONString(response.getHits()));
  24. for (SearchHit documentFields : response.getHits().getHits()) {
  25. System.out.println(documentFields.getSourceAsMap());
  26. }
  27. restHighLevelClient.close();
  28. }

控制台日志如下:

  1. {"fragment":true,"hits":[{"fields":{},"fragment":false,"highlightFields":{},"id":"1","matchedQueries":[],"primaryTerm":0,"rawSortValues":[],"score":1.3862942,"seqNo":-2,"sortValues":[],"sourceAsMap":{"name":"张三","age":10},"sourceAsString":"{\"age\":10,\"name\":\"张三\"}","sourceRef":{"fragment":true},"type":"_doc","version":-1}],"maxScore":1.3862942,"totalHits":{"relation":"EQUAL_TO","value":1}}
  2. {name=张三, age=10}

【e】范围查询

  • QueryBuilders.rangeQuery("age")
  1. /**
  2. * 范围查询
  3. */
  4. @Test
  5. void rangeSearch() throws IOException {
  6. SearchRequest searchRequest = new SearchRequest("student_info");
  7. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  8. //构建bool查询
  9. BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
  10. //年龄大于等于20,小于等于40的记录
  11. boolQueryBuilder.must(
  12. QueryBuilders.rangeQuery("age") //指定范围查询的字段
  13. .gte("20")
  14. .lte("50")
  15. );
  16. searchSourceBuilder.query(boolQueryBuilder);
  17. searchRequest.source(searchSourceBuilder);
  18. SearchResponse response = null;
  19. try {
  20. response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
  21. } catch (IOException e) {
  22. e.printStackTrace();
  23. }
  24. //循环遍历查询结果
  25. System.out.println(JSON.toJSONString(response.getHits()));
  26. for (SearchHit documentFields : response.getHits().getHits()) {
  27. System.out.println(documentFields.getSourceAsMap());
  28. }
  29. restHighLevelClient.close();
  30. }

控制台日志如下:

  1. {"fragment":true,"hits":[{"fields":{},"fragment":false,"highlightFields":{},"id":"2","matchedQueries":[],"primaryTerm":0,"rawSortValues":[],"score":1.0,"seqNo":-2,"sortValues":[],"sourceAsMap":{"name":"李四","age":20},"sourceAsString":"{\"age\":20,\"name\":\"李四\"}","sourceRef":{"fragment":true},"type":"_doc","version":-1},{"fields":{},"fragment":false,"highlightFields":{},"id":"3","matchedQueries":[],"primaryTerm":0,"rawSortValues":[],"score":1.0,"seqNo":-2,"sortValues":[],"sourceAsMap":{"name":"王五","age":30},"sourceAsString":"{\"age\":30,\"name\":\"王五\"}","sourceRef":{"fragment":true},"type":"_doc","version":-1},{"fields":{},"fragment":false,"highlightFields":{},"id":"4","matchedQueries":[],"primaryTerm":0,"rawSortValues":[],"score":1.0,"seqNo":-2,"sortValues":[],"sourceAsMap":{"name":"赵六","age":40},"sourceAsString":"{\"age\":40,\"name\":\"赵六\"}","sourceRef":{"fragment":true},"type":"_doc","version":-1},{"fields":{},"fragment":false,"highlightFields":{},"id":"5","matchedQueries":[],"primaryTerm":0,"rawSortValues":[],"score":1.0,"seqNo":-2,"sortValues":[],"sourceAsMap":{"name":"田七","age":50},"sourceAsString":"{\"age\":50,\"name\":\"田七\"}","sourceRef":{"fragment":true},"type":"_doc","version":-1}],"maxScore":1.0,"totalHits":{"relation":"EQUAL_TO","value":4}}
  2. {name=李四, age=20}
  3. {name=王五, age=30}
  4. {name=赵六, age=40}
  5. {name=田七, age=50}

【f】must与查询(相当于and)

  • must表示符合条件的,相反的mustnot表示不符合条件的。
  1. /**
  2. * must与查询(相当于and)
  3. */
  4. @Test
  5. void mustQuery() {
  6. //构造查询请求
  7. SearchRequest searchRequest = new SearchRequest("student_info");
  8. //构造SearchSourceBuilder
  9. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  10. //构造bool查询
  11. BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
  12. /**
  13. * must: and且查询
  14. * select * from xxx where name (like '%张%' ) and (age >= 10 and age <= 20)
  15. */
  16. //1.范围查询: 年龄大于等于10、小于等于20的记录
  17. RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("age");
  18. rangeQueryBuilder.lte(20).gte(10);
  19. boolQueryBuilder.must(rangeQueryBuilder);
  20. //2.match匹配查询: 姓名中包含"张"的记录
  21. MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("name", "张");
  22. boolQueryBuilder.must(matchQueryBuilder);
  23. searchSourceBuilder.query(boolQueryBuilder);
  24. searchRequest.source(searchSourceBuilder);
  25. SearchResponse response = null;
  26. try {
  27. //执行请求,返回响应结果
  28. response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
  29. } catch (IOException e) {
  30. e.printStackTrace();
  31. }
  32. System.out.println(JSON.toJSONString(response.getHits()));
  33. for (SearchHit searchHit : response.getHits().getHits()) {
  34. System.out.println(searchHit.getSourceAsMap());
  35. }
  36. }

控制台日志如下:

  1. {"fragment":true,"hits":[{"fields":{},"fragment":false,"highlightFields":{},"id":"1","matchedQueries":[],"primaryTerm":0,"rawSortValues":[],"score":2.3862944,"seqNo":-2,"sortValues":[],"sourceAsMap":{"name":"张三","age":10},"sourceAsString":"{\"age\":10,\"name\":\"张三\"}","sourceRef":{"fragment":true},"type":"_doc","version":-1}],"maxScore":2.3862944,"totalHits":{"relation":"EQUAL_TO","value":1}}
  2. {name=张三, age=10}

【g】should或查询(相当于or)

  1. /**
  2. * should或查询(相当于or)
  3. */
  4. @Test
  5. void shouldQuery() {
  6. //构造查询请求
  7. SearchRequest searchRequest = new SearchRequest("student_info");
  8. //构造SearchSourceBuilder
  9. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  10. //构造bool查询
  11. BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
  12. /**
  13. * should: or或查询
  14. * select * from xxx where name (like '%张%' ) or (age >= 10 and age <= 20)
  15. */
  16. //1.范围查询: 年龄大于等于10、小于等于20的记录
  17. RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("age");
  18. rangeQueryBuilder.lte(20).gte(10);
  19. boolQueryBuilder.should(rangeQueryBuilder);
  20. //2.match匹配查询: 姓名中包含"张"的记录
  21. MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("name", "张");
  22. boolQueryBuilder.should(matchQueryBuilder);
  23. searchSourceBuilder.query(boolQueryBuilder);
  24. searchRequest.source(searchSourceBuilder);
  25. SearchResponse response = null;
  26. try {
  27. //执行请求,返回响应结果
  28. response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
  29. } catch (IOException e) {
  30. e.printStackTrace();
  31. }
  32. System.out.println(JSON.toJSONString(response.getHits()));
  33. for (SearchHit searchHit : response.getHits().getHits()) {
  34. System.out.println(searchHit.getSourceAsMap());
  35. }
  36. }

控制台日志如下:

  1. {"fragment":true,"hits":[{"fields":{},"fragment":false,"highlightFields":{},"id":"1","matchedQueries":[],"primaryTerm":0,"rawSortValues":[],"score":2.3862944,"seqNo":-2,"sortValues":[],"sourceAsMap":{"name":"张三","age":10},"sourceAsString":"{\"age\":10,\"name\":\"张三\"}","sourceRef":{"fragment":true},"type":"_doc","version":-1},{"fields":{},"fragment":false,"highlightFields":{},"id":"2","matchedQueries":[],"primaryTerm":0,"rawSortValues":[],"score":1.0,"seqNo":-2,"sortValues":[],"sourceAsMap":{"name":"李四","age":20},"sourceAsString":"{\"age\":20,\"name\":\"李四\"}","sourceRef":{"fragment":true},"type":"_doc","version":-1}],"maxScore":2.3862944,"totalHits":{"relation":"EQUAL_TO","value":2}}
  2. {name=张三, age=10}
  3. {name=李四, age=20}

【h】带排序的搜索

SearchSourceBuilder的排序:允许添加一个或多个SortBuilder实例,有四种特殊的实现(Field-,Score-,GeoDistance-和ScriptSortBuilder)。

  1. sourceBuilder.sort(new ScoreSortBuilder().order(SortOrder.DESC));    //按_score降序排序(默认值) 
  2. sourceBuilder.sort(new FieldSortBuilder("_id").order(SortOrder.ASC));    //按_id字段进行升序排序
  • searchSourceBuilder.sort("age", SortOrder.DESC);
  1. /**
  2. * 带排序的搜索: searchSourceBuilder.sort("age", SortOrder.DESC);
  3. */
  4. @Test
  5. void sortQuery() throws IOException {
  6. SearchRequest searchRequest = new SearchRequest("student_info");
  7. //构建搜索条件
  8. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  9. MatchAllQueryBuilder matchAllQueryBuilder = QueryBuilders.matchAllQuery();
  10. searchSourceBuilder.query(matchAllQueryBuilder);
  11. //设置超时时间
  12. searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
  13. //按age降序排序
  14. searchSourceBuilder.sort("age", SortOrder.DESC);
  15. searchRequest.source(searchSourceBuilder);
  16. SearchResponse response = null;
  17. try {
  18. //执行查询请求,获取响应结果
  19. response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
  20. } catch (IOException e) {
  21. e.printStackTrace();
  22. }
  23. //循环遍历查询结果
  24. System.out.println(JSON.toJSONString(response.getHits()));
  25. for (SearchHit documentFields : response.getHits().getHits()) {
  26. System.out.println(documentFields.getSourceAsMap());
  27. }
  28. restHighLevelClient.close();
  29. }

控制台日志如下:

  1. {"fragment":true,"hits":[{"fields":{},"fragment":false,"highlightFields":{},"id":"5","matchedQueries":[],"primaryTerm":0,"rawSortValues":[],"score":null,"seqNo":-2,"sortValues":[50],"sourceAsMap":{"name":"田七","age":50},"sourceAsString":"{\"age\":50,\"name\":\"田七\"}","sourceRef":{"fragment":true},"type":"_doc","version":-1},{"fields":{},"fragment":false,"highlightFields":{},"id":"4","matchedQueries":[],"primaryTerm":0,"rawSortValues":[],"score":null,"seqNo":-2,"sortValues":[40],"sourceAsMap":{"name":"赵六","age":40},"sourceAsString":"{\"age\":40,\"name\":\"赵六\"}","sourceRef":{"fragment":true},"type":"_doc","version":-1},{"fields":{},"fragment":false,"highlightFields":{},"id":"3","matchedQueries":[],"primaryTerm":0,"rawSortValues":[],"score":null,"seqNo":-2,"sortValues":[30],"sourceAsMap":{"name":"王五","age":30},"sourceAsString":"{\"age\":30,\"name\":\"王五\"}","sourceRef":{"fragment":true},"type":"_doc","version":-1},{"fields":{},"fragment":false,"highlightFields":{},"id":"2","matchedQueries":[],"primaryTerm":0,"rawSortValues":[],"score":null,"seqNo":-2,"sortValues":[20],"sourceAsMap":{"name":"李四","age":20},"sourceAsString":"{\"age\":20,\"name\":\"李四\"}","sourceRef":{"fragment":true},"type":"_doc","version":-1},{"fields":{},"fragment":false,"highlightFields":{},"id":"1","matchedQueries":[],"primaryTerm":0,"rawSortValues":[],"score":null,"seqNo":-2,"sortValues":[10],"sourceAsMap":{"name":"张三","age":10},"sourceAsString":"{\"age\":10,\"name\":\"张三\"}","sourceRef":{"fragment":true},"type":"_doc","version":-1}],"maxScore":null,"totalHits":{"relation":"EQUAL_TO","value":5}}
  2. {name=田七, age=50}
  3. {name=赵六, age=40}
  4. {name=王五, age=30}
  5. {name=李四, age=20}
  6. {name=张三, age=10}

【i】分页搜索

  • searchSourceBuilder.from(1);    //设置确定结果要从哪个索引开始搜索的from选项,默认为0
  • searchSourceBuilder.size(2);    //设置确定搜素命中返回数的size选项,默认为10
  1. /**
  2. * 分页搜索: searchSourceBuilder.from(1); searchSourceBuilder.size(2);
  3. */
  4. @Test
  5. void paginationQuery() throws IOException {
  6. SearchRequest searchRequest = new SearchRequest("student_info");
  7. //构建搜索条件
  8. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  9. MatchAllQueryBuilder matchAllQueryBuilder = QueryBuilders.matchAllQuery();
  10. searchSourceBuilder.query(matchAllQueryBuilder);
  11. //设置超时时间
  12. searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
  13. //按age降序排序
  14. searchSourceBuilder.sort("age", SortOrder.DESC);
  15. //从第一条记录开始,每页展示两条
  16. searchSourceBuilder.from(1);
  17. searchSourceBuilder.size(2);
  18. searchRequest.source(searchSourceBuilder);
  19. SearchResponse response = null;
  20. try {
  21. //执行查询请求,获取响应结果
  22. response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
  23. } catch (IOException e) {
  24. e.printStackTrace();
  25. }
  26. //循环遍历查询结果
  27. System.out.println(JSON.toJSONString(response.getHits()));
  28. for (SearchHit documentFields : response.getHits().getHits()) {
  29. System.out.println(documentFields.getSourceAsMap());
  30. }
  31. restHighLevelClient.close();
  32. }

控制台日志如下:

  1. {"fragment":true,"hits":[{"fields":{},"fragment":false,"highlightFields":{},"id":"4","matchedQueries":[],"primaryTerm":0,"rawSortValues":[],"score":null,"seqNo":-2,"sortValues":[40],"sourceAsMap":{"name":"赵六","age":40},"sourceAsString":"{\"age\":40,\"name\":\"赵六\"}","sourceRef":{"fragment":true},"type":"_doc","version":-1},{"fields":{},"fragment":false,"highlightFields":{},"id":"3","matchedQueries":[],"primaryTerm":0,"rawSortValues":[],"score":null,"seqNo":-2,"sortValues":[30],"sourceAsMap":{"name":"王五","age":30},"sourceAsString":"{\"age\":30,\"name\":\"王五\"}","sourceRef":{"fragment":true},"type":"_doc","version":-1}],"maxScore":null,"totalHits":{"relation":"EQUAL_TO","value":5}}
  2. {name=赵六, age=40}
  3. {name=王五, age=30}

【j】高亮搜索

通过在SearchSourceBuilder上设置HighlightBuilder,可以实现高亮搜索结果。

  • HighlightBuilder highlightBuilder = new HighlightBuilder();
  • highlightBuilder.field("name"); 
  • highlightBuilder.preTags("<span style=\"color:red\">");
  • highlightBuilder.postTags("</span>");
  • searchSourceBuilder.highlighter(highlightBuilder);
  1. /**
  2. * 高亮显示搜索
  3. */
  4. @Test
  5. void highLightQuery() throws IOException {
  6. SearchRequest searchRequest = new SearchRequest("student_info");
  7. //构建搜索条件
  8. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  9. MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("name", "张");
  10. //设置超时时间
  11. searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
  12. //按age降序排序
  13. searchSourceBuilder.sort("age", SortOrder.DESC);
  14. HighlightBuilder highlightBuilder = new HighlightBuilder();
  15. //指定高亮字段
  16. highlightBuilder.field("name");
  17. //指定前置标签
  18. highlightBuilder.preTags("<span style=\"color:red\">");
  19. //指定后置标签
  20. highlightBuilder.postTags("</span>");
  21. searchSourceBuilder.highlighter(highlightBuilder);
  22. searchSourceBuilder.query(matchQueryBuilder);
  23. searchRequest.source(searchSourceBuilder);
  24. SearchResponse response = null;
  25. try {
  26. //执行查询请求,获取响应结果
  27. response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
  28. } catch (IOException e) {
  29. e.printStackTrace();
  30. }
  31. //循环遍历查询结果
  32. System.out.println(JSON.toJSONString(response.getHits()));
  33. for (SearchHit searchHit : response.getHits().getHits()) {
  34. Map<String, Object> sourceAsMap = searchHit.getSourceAsMap();
  35. //获取对应的高亮域
  36. Map<String, HighlightField> highlightFields = searchHit.getHighlightFields();
  37. //获取高亮字段
  38. HighlightField name = highlightFields.get("name");
  39. if (null != name) {
  40. // 为name串值增加自定义的高亮标签
  41. Text[] nameTexts = name.fragments();
  42. StringBuilder newName = new StringBuilder();
  43. for (Text text : nameTexts) {
  44. newName.append(text);
  45. }
  46. //将追加了高亮标签的串值重新填充到对应的对象
  47. sourceAsMap.put("name", newName.toString());
  48. }
  49. System.out.println(sourceAsMap);
  50. }
  51. restHighLevelClient.close();
  52. }

控制台日志输出:

  1. {"fragment":true,"hits":[{"fields":{},"fragment":false,"highlightFields":{"name":{"fragment":true,"fragments":[{"fragment":true}],"name":"name"}},"id":"1","matchedQueries":[],"primaryTerm":0,"rawSortValues":[],"score":null,"seqNo":-2,"sortValues":[10],"sourceAsMap":{"name":"张三","age":10},"sourceAsString":"{\"age\":10,\"name\":\"张三\"}","sourceRef":{"fragment":true},"type":"_doc","version":-1}],"maxScore":null,"totalHits":{"relation":"EQUAL_TO","value":1}}
  2. {name=<span style="color:red"></span>三, age=10}

【k】一次查询多个条件

  • MultiSearchRequest multiSearchRequest = new MultiSearchRequest();
  • restHighLevelClient.msearch(multiSearchRequest, RequestOptions.DEFAULT)
  1. /**
  2. * 一次查询多个条件: restHighLevelClient.msearch(multiSearchRequest, RequestOptions.DEFAULT)
  3. */
  4. @Test
  5. void multiSearchQuery() throws IOException {
  6. //构造请求MultiSearchRequest
  7. MultiSearchRequest multiSearchRequest = new MultiSearchRequest();
  8. /*
  9. * 第一个SearchRequest
  10. */
  11. SearchRequest firstSearchRequest = new SearchRequest("student_info");
  12. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  13. MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("name", "张");
  14. searchSourceBuilder.query(matchQueryBuilder);
  15. firstSearchRequest.source(searchSourceBuilder);
  16. multiSearchRequest.add(firstSearchRequest);
  17. /*
  18. * 第二个SearchRequest
  19. */
  20. SearchRequest secondSearchRequest = new SearchRequest("student_info");
  21. searchSourceBuilder = new SearchSourceBuilder();
  22. matchQueryBuilder = QueryBuilders.matchQuery("name", "李");
  23. searchSourceBuilder.query(matchQueryBuilder);
  24. secondSearchRequest.source(searchSourceBuilder);
  25. multiSearchRequest.add(secondSearchRequest);
  26. MultiSearchResponse multiSearchResponse;
  27. try {
  28. //执行请求,返回多个响应
  29. multiSearchResponse = restHighLevelClient.msearch(multiSearchRequest, RequestOptions.DEFAULT);
  30. multiSearchResponse.forEach(t -> {
  31. SearchResponse response = t.getResponse();
  32. //循环遍历查询结果
  33. System.out.println(JSON.toJSONString(response.getHits()));
  34. for (SearchHit searchHit : response.getHits().getHits()) {
  35. System.out.println(searchHit.getSourceAsMap());
  36. }
  37. });
  38. } catch (IOException e) {
  39. e.printStackTrace();
  40. }
  41. restHighLevelClient.close();
  42. }

 控制台日志输出:

  1. {"fragment":true,"hits":[{"fields":{},"fragment":false,"highlightFields":{},"id":"1","matchedQueries":[],"primaryTerm":0,"rawSortValues":[],"score":1.3862942,"seqNo":-2,"sortValues":[],"sourceAsMap":{"name":"张三","age":10},"sourceAsString":"{\"age\":10,\"name\":\"张三\"}","sourceRef":{"fragment":true},"type":"_doc","version":-1}],"maxScore":1.3862942,"totalHits":{"relation":"EQUAL_TO","value":1}}
  2. {name=张三, age=10}
  3. {"fragment":true,"hits":[{"fields":{},"fragment":false,"highlightFields":{},"id":"2","matchedQueries":[],"primaryTerm":0,"rawSortValues":[],"score":1.3862942,"seqNo":-2,"sortValues":[],"sourceAsMap":{"name":"李四","age":20},"sourceAsString":"{\"age\":20,\"name\":\"李四\"}","sourceRef":{"fragment":true},"type":"_doc","version":-1}],"maxScore":1.3862942,"totalHits":{"relation":"EQUAL_TO","value":1}}
  4. {name=李四, age=20}

三、总结

以上总结了一些常见的ES Java客户端查询API相关的示例,在实际项目中,得根据具体的业务需求,灵活构造不同的xxxQueryBuilder实现。希望以上代码可以帮助到读者,也能为以后再次使用时提供帮助。由于笔者水平有限,以上如有不对之处,还望指正,相互学习,一起进步!

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

闽ICP备14008679号