当前位置:   article > 正文

使用RestHighLevelClient 请求ES数据_resthighlevelclient.search(searchrequest, requesto

resthighlevelclient.search(searchrequest, requestoptions.default);

目录

过程:

0,引用:

1,RestHighLevelClient 查询的方式:

代码:

2,EsQuery查参数

3,EsOrder排序:

4,SearchEsHits

总结:


RestHighLevelClient 请求ES数据

使用Java请求es,如何使用RestHighLevelClient 进行请求查询,获取到数据呢?

过程:

0,引用:

引用文件:

 

Maven:

  1. <dependency>
  2.    <groupId>org.elasticsearch</groupId>
  3.    <artifactId>elasticsearch</artifactId>
  4.    <version>6.8.2</version>
  5. </dependency>
  6. <dependency>
  7.    <groupId>org.elasticsearch.client</groupId>
  8.    <artifactId>elasticsearch-rest-high-level-client</artifactId>
  9.    <version>6.8.2</version>
  10. </dependency>
  11. <dependency>
  12.    <groupId>org.elasticsearch.client</groupId>
  13.    <artifactId>elasticsearch-rest-client</artifactId>
  14.    <version>6.8.2</version>
  15. </dependency>
  16. <dependency>
  17.    <groupId>org.elasticsearch.client</groupId>
  18.    <artifactId>x-pack-transport</artifactId>
  19.    <version>6.8.12</version>
  20. </dependency>

Yml:

  1. elasticsearch:
  2. cluster:
  3. name: elastic
  4. hosts: ip:port
  5. address: ip:port
  6. xpack:
  7. security:
  8. user: elastic:elastic
  9. enabled: true

1,RestHighLevelClient 查询的方式:

  1. public void getHisResultOri() {
  2.     SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  3.     SearchRequest searchRequest = new SearchRequest();
  4.     // 查询的索引
  5.     searchRequest.indices("check_data_index");
  6.     // query 的查询
  7.     QueryBuilder queryBuilder = QueryBuilders.wrapperQuery("{\"bool\":{\"must\":{\"terms\":{\"make.keyword\":[\"toyota\"]}}}}");
  8.     searchSourceBuilder.query(queryBuilder);
  9.     searchRequest.source(searchSourceBuilder);
  10.     // 排序
  11.     searchSourceBuilder.sorts().add(SortBuilders.fieldSort("price").order(SortOrder.fromString("desc")));
  12.     // from size
  13.     searchSourceBuilder.from(0);
  14.     searchSourceBuilder.size(10);
  15.     try {
  16.         SearchResponse searchResponse = highLevelClient.search(searchRequest, RequestOptions.DEFAULT);
  17.         logger.info(JSON.toJSONString(searchResponse));
  18.         SearchHits hits = searchResponse.getHits();
  19.         SearchHit[] searchHits = hits.getHits();
  20.         logger.info("search hit size :{},{}", hits.getTotalHits(), searchHits.length);
  21.     } catch (IOException e) {
  22.         e.printStackTrace();
  23.     }
  24. }

分析:

在查询中,设置索引,query的查询参数,排序,开始(from),个数(size),五个的内容。 排序 包括 字段和排序方式。简易的添加两个相关的类:

代码:

2,EsQuery查参数

  1. import io.swagger.annotations.ApiModel;
  2. import io.swagger.annotations.ApiModelProperty;
  3. import java.util.List;
  4. @ApiModel(value = "es查询参数")
  5. public class EsQuery {
  6.     @ApiModelProperty("es索引")
  7.     private String sourceIndex;
  8.     @ApiModelProperty("第几页")
  9.     private Integer page;
  10.     @ApiModelProperty("分页大小")
  11.     private Integer size;
  12.     @ApiModelProperty("查询参数")
  13.     private String sourceExpr;
  14.     @ApiModelProperty("排序")
  15.     private List<EsOrder> orders;
  16.     public String getSourceIndex() {
  17.         return sourceIndex;
  18.     }
  19.     public void setSourceIndex(String sourceIndex) {
  20.         this.sourceIndex = sourceIndex;
  21.     }
  22.     public Integer getPage() {
  23.         return page;
  24.     }
  25.     public void setPage(Integer page) {
  26.         this.page = page;
  27.     }
  28.     public Integer getSize() {
  29.         return size;
  30.     }
  31.     public void setSize(Integer size) {
  32.         this.size = size;
  33.     }
  34.     public String getSourceExpr() {
  35.         return sourceExpr;
  36.     }
  37.     public void setSourceExpr(String sourceExpr) {
  38.         this.sourceExpr = sourceExpr;
  39.     }
  40.     public List<EsOrder> getOrders() {
  41.         return orders;
  42.     }
  43.     public void setOrders(List<EsOrder> orders) {
  44.         this.orders = orders;
  45.     }
  46.     @Override
  47.     public String toString() {
  48.         return "{" +
  49.                 "sourceIndex='" + sourceIndex + '\'' +
  50.                 ", page=" + page +
  51.                 ", size=" + size +
  52.                 ", sourceExpr='" + sourceExpr + '\'' +
  53.                 ", orders=" + orders +
  54.                 '}';
  55.     }
  56. }

3,EsOrder排序:

  1. import io.swagger.annotations.ApiModel;
  2. import io.swagger.annotations.ApiModelProperty;
  3. @ApiModel(value = "es排序")
  4. public class EsOrder {
  5. @ApiModelProperty("排序字段")
  6. private String fieldName;
  7. @ApiModelProperty("排序方式:ASC,DESC")
  8. private String orderBy;
  9. public EsOrder(String fieldName, String orderBy) {
  10. this.fieldName = fieldName;
  11. this.orderBy = orderBy;
  12. }
  13. public String getFieldName() {
  14. return fieldName;
  15. }
  16. public void setFieldName(String fieldName) {
  17. this.fieldName = fieldName;
  18. }
  19. public String getOrderBy() {
  20. return orderBy;
  21. }
  22. public void setOrderBy(String orderBy) {
  23. this.orderBy = orderBy;
  24. }
  25. }

4SearchEsHits

  1. import com.alibaba.fastjson.JSON;
  2. import com.alibaba.fastjson.JSONObject;
  3. import es.search.highLevel.entity.EsOrder;
  4. import es.search.highLevel.entity.EsQuery;
  5. import org.apache.commons.collections4.CollectionUtils;
  6. import org.elasticsearch.action.search.SearchRequest;
  7. import org.elasticsearch.action.search.SearchResponse;
  8. import org.elasticsearch.client.RequestOptions;
  9. import org.elasticsearch.client.RestHighLevelClient;
  10. import org.elasticsearch.index.query.QueryBuilder;
  11. import org.elasticsearch.index.query.QueryBuilders;
  12. import org.elasticsearch.search.SearchHit;
  13. import org.elasticsearch.search.SearchHits;
  14. import org.elasticsearch.search.builder.SearchSourceBuilder;
  15. import org.elasticsearch.search.sort.FieldSortBuilder;
  16. import org.elasticsearch.search.sort.SortOrder;
  17. import org.slf4j.Logger;
  18. import org.slf4j.LoggerFactory;
  19. import org.springframework.beans.factory.annotation.Autowired;
  20. import java.io.IOException;
  21. import java.util.ArrayList;
  22. import java.util.List;
  23. public class SearchEsHits {
  24. @Autowired
  25. private RestHighLevelClient highLevelClient;
  26. private static Logger logger = LoggerFactory.getLogger(SearchEsHits.class);
  27. public void getHitsResult(EsQuery esQuery) {
  28. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  29. SearchRequest searchRequest = new SearchRequest();
  30. // 查询的索引
  31. searchRequest.indices(esQuery.getSourceIndex());
  32. // query 的查询
  33. String sourceExpr = esQuery.getSourceExpr();
  34. if (sourceExpr.contains("query")) {// 带有query的查询
  35. sourceExpr = JSONObject.parseObject(sourceExpr).getJSONObject("query").toJSONString();
  36. }
  37. QueryBuilder queryBuilder = QueryBuilders.wrapperQuery(sourceExpr);
  38. searchSourceBuilder.query(queryBuilder);
  39. searchRequest.source(searchSourceBuilder);
  40. // 排序
  41. List<EsOrder> orders = esQuery.getOrders();
  42. if (CollectionUtils.isNotEmpty(orders)) {
  43. for (EsOrder e : orders) {
  44. searchSourceBuilder.sort(new FieldSortBuilder(e.getFieldName()).order(SortOrder.fromString(e.getOrderBy())));
  45. }
  46. }
  47. // from size
  48. int start = esQuery.getPage() * esQuery.getSize();
  49. searchSourceBuilder.from(start);
  50. searchSourceBuilder.size(esQuery.getSize());
  51. try {
  52. SearchResponse searchResponse = highLevelClient.search(searchRequest, RequestOptions.DEFAULT);
  53. logger.info(JSON.toJSONString(searchResponse));
  54. SearchHits hits = searchResponse.getHits();
  55. List<JSONObject> hitsList = new ArrayList<>();
  56. SearchHit[] searchHits = hits.getHits();
  57. logger.info("search hit size :{},{}", hits.getTotalHits(), searchHits.length);
  58. for (SearchHit hit : searchHits) {
  59. String result = hit.getSourceAsString();
  60. JSONObject jsonObject = JSONObject.parseObject(result);
  61. hitsList.add(jsonObject);
  62. }
  63. } catch (IOException e) {
  64. e.printStackTrace();
  65. }
  66. }
  67. }

PS: 这边没有对返回值,总数进一步处理,可以根据自己的需求再处理。

总结:

        使用RestHighLevelClient查询es数据,可以使用QueryBuilders.wrapperQuery(sourceExpr)处理query的数据就会方便很多,使用boolQuery查询的话,会比较崩溃。查询聚合的方式就不得不单独处理了。

关联文章: 《使用commons-httpclinet 请求ES数据》

下一篇: 《使用RestHighLevelClient 请求ES统计数据》

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

闽ICP备14008679号