当前位置:   article > 正文

java实现 elasticsearch es 的单个条件查询和多个条件查询,根据id更新指定字段_searchsourcebuilder多条件查询

searchsourcebuilder多条件查询

先注入

  1. @Autowired
  2. private RestHighLevelClient restHighLevelClient;

1:ES根据单个条件查询

  1. public String searchEsAttachmentsLink(String riskId,String dataFrom){
  2. try {
  3. //添加条件,
  4. SearchSourceBuilder searchSourceBuilder = SearchSourceBuilder.searchSource()
  5. .size(1)
  6. .query(QueryBuilders.termQuery( name: "字段", 值));
  7. //拼装
  8. SearchRequest searchRequest = new SearchRequest()
  9. .indices(索引)
  10. .source(searchSourceBuilder);
  11. //用ESClient执行search,得到响应结果
  12. SearchResponse searchResponse =
  13. restHighLevelClient.search(searchRequest,RequestOption.DEFAULT);
  14. //根据自己返回的数据格式取值
  15. SearchHit[] hits = searchResponse.getHits().getHits();
  16. for (SearchHit hit : hits) {
  17. //取值
  18. hit.getSourceAsMap().get("字段");
  19. }
  20. return null;
  21. }

2:ES根据多个条件查询

  1. BoolOueryBuilder boolOueryBuilder = new BoolOueryBuilder();
  2. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  3. //用must拼接where条件
  4. boolQueryBuilder.must(QueryBuilders.termQuery("字段""值"))
  5. .must(QueryBuilders.termQuery("字段","值");
  6. SearchRequest searchRequest = new SearchRequest()
  7. .indices(索引)
  8. .source(searchSourceBuilder);
  9. searchSourceBuilder.query(boolQueryBuilder);
  10. log.info("拼接后的请求参数: ",searchRequest);
  11. SearchResponse searchResponse = restHighLevelclient.search(searchRequest,RequestOptions .DEFAULT) ;
  12. log.info("查询后的结果: ",searchResponse);
  13. //取值
  14. SearchHitl] hits = searchResponse.getHits() .getHits();

3:ES根据id,局部更新文档

  1. UpdateRequest updateRequest = new UpdateRequest();
  2. updateRequest.index(索引);
  3. updateRequest.type("_doc");
  4. updateRequest.id(id);
  5. //添加where条件
  6. updateRequest.doc(
  7. XContentFactory.jsonBuilder(
  8. .startobject()
  9. .field( "字段""值")
  10. .field( "字段""值")
  11. .endobject()
  12. );
  13. //执行
  14. String resultUpdate = restHighlevelClient.update(updateRequest, Request0ptions.DEFAULT).getResult().tostring();

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

闽ICP备14008679号