赞
踩
初始化:
- RestHighLevelClient client = new RestHighLevelClient(
- RestClient.builder(
- new HttpHost("localhost", 9200, "http"),
- new HttpHost("localhost", 9201, "http")));
The high-level client 是比low-level更进一层的封装,两者性能相差不大。
highlevel兼容性更好,API丰富,适合于高并发场景,且highlvel的内部基于low level(维护连接池和启动线程),所以hghlevel要正确的关闭才会把内部的lowlevelclient一起关闭,
关闭方式:
client.close();
搜索查询search API
- //创建搜索请求
- SearchRequest searchRequest = new SearchRequest();
- //将查询设置和参数添加到searchsourcebuilder
- SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
- //将match_all添加到ssb
- searchSourceBuilder.query(QueryBuilders.matchAllQuery());
- //最后将查询的结构添加到查询请求中
- searchRequest.source(searchSourceBuilder);
-
-
- 单个查询示例:
-
- SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
- sourceBuilder.query(QueryBuilders.termQuery("user", "kimchy"));
- sourceBuilder.from(0);
- sourceBuilder.size(5);
- sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
-
- SearchRequest searchRequest = new SearchRequest();
- searchRequest.indices("posts");
- searchRequest.source(sourceBuilder);
-
同步获取返回值,会可能会引发IO错误,需要捕捉错误信息
- //同步执行,获取返回值
- SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
异步获取返回值,不会阻塞和立马返回。一旦执行完成,会调用ActionListener,成功调用onResponse,失败调用onFailure
- client.searchAsync(searchRequest, RequestOptions.DEFAULT, listener);
-
-
- 通用的listener:
- ActionListener<SearchResponse> listener = new ActionListener<SearchResponse>() {
- @Override
- public void onResponse(SearchResponse searchResponse) {
-
- }
-
- @Override
- public void onFailure(Exception e) {
-
- }
- };
返回值接收 SearchResponse
- //获取返回值的状态码
- RestStatus status = searchResponse.status();
- //查询所用时间
- TimeValue took = searchResponse.getTook();
- //执行时间或请求是提前终止还是超时:
- Boolean terminatedEarly = searchResponse.isTerminatedEarly();
- boolean timedOut = searchResponse.isTimedOut();
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。