当前位置:   article > 正文

java rest client初始化和搜索查询--es_java方式执行es查询语句

java方式执行es查询语句

初始化

  1. RestHighLevelClient client = new RestHighLevelClient(
  2. RestClient.builder(
  3. new HttpHost("localhost", 9200, "http"),
  4. new HttpHost("localhost", 9201, "http")));

The high-level client 是比low-level更进一层的封装,两者性能相差不大。

highlevel兼容性更好,API丰富,适合于高并发场景,且highlvel的内部基于low level(维护连接池和启动线程),所以hghlevel要正确的关闭才会把内部的lowlevelclient一起关闭,

关闭方式:

client.close();

搜索查询search API

  1. //创建搜索请求
  2. SearchRequest searchRequest = new SearchRequest();
  3. //将查询设置和参数添加到searchsourcebuilder
  4. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  5. //将match_all添加到ssb
  6. searchSourceBuilder.query(QueryBuilders.matchAllQuery());
  7. //最后将查询的结构添加到查询请求中
  8. searchRequest.source(searchSourceBuilder);
  9. 单个查询示例:
  10. SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
  11. sourceBuilder.query(QueryBuilders.termQuery("user", "kimchy"));
  12. sourceBuilder.from(0);
  13. sourceBuilder.size(5);
  14. sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
  15. SearchRequest searchRequest = new SearchRequest();
  16. searchRequest.indices("posts");
  17. searchRequest.source(sourceBuilder);

同步获取返回值,会可能会引发IO错误,需要捕捉错误信息

  1. //同步执行,获取返回值
  2. SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

异步获取返回值,不会阻塞和立马返回。一旦执行完成,会调用ActionListener,成功调用onResponse,失败调用onFailure

  1. client.searchAsync(searchRequest, RequestOptions.DEFAULT, listener);
  2. 通用的listener:
  3. ActionListener<SearchResponse> listener = new ActionListener<SearchResponse>() {
  4. @Override
  5. public void onResponse(SearchResponse searchResponse) {
  6. }
  7. @Override
  8. public void onFailure(Exception e) {
  9. }
  10. };

返回值接收 SearchResponse

  1. //获取返回值的状态码
  2. RestStatus status = searchResponse.status();
  3. //查询所用时间
  4. TimeValue took = searchResponse.getTook();
  5. //执行时间或请求是提前终止还是超时:
  6. Boolean terminatedEarly = searchResponse.isTerminatedEarly();
  7. boolean timedOut = searchResponse.isTimedOut();

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

闽ICP备14008679号