ElasticSearch High Level REST API(4)多搜索

Multi-Search多搜索请求

Multi-Search可同时添加多个search搜索请求,并行地在一个http请求中执行多个搜索请求,相较多次单请求查询可提升查询效率。ES客户端通过mget方法实现多请求搜索:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
@GetMapping("multiSearch")
public void multiSearch() {
MultiSearchRequest request = new MultiSearchRequest();
SearchRequest firstRequest = new SearchRequest("appblog");
SearchSourceBuilder firstBuilder = new SearchSourceBuilder();
firstBuilder.query(QueryBuilders.matchQuery("loglvl", "ERROR"));
firstBuilder.sort("@timestamp", SortOrder.DESC);
firstBuilder.from(0);
firstBuilder.size(5);
firstRequest.source(firstBuilder);
request.add(firstRequest);
SearchRequest secondRequest = new SearchRequest();
SearchSourceBuilder secondBuild = new SearchSourceBuilder();
secondBuild.query(QueryBuilders.matchQuery("name", "Joe.Ye"));
secondRequest.source(secondBuild);
request.add(secondRequest);
try {
MultiSearchResponse multiResponse = client.msearch(request, RequestOptions.DEFAULT);
MultiSearchResponse.Item firstItem = multiResponse.getResponses()[0];
if (firstItem.getFailure() != null) {
System.out.println("First search request fail!");
}
SearchResponse firstResponse = firstItem.getResponse();
for (SearchHit documentFields : firstResponse.getHits().getHits()) {
System.out.println("First search response: " + documentFields.getSourceAsString());
}
MultiSearchResponse.Item secondItem = multiResponse.getResponses()[1];
if (secondItem.getFailure() != null) {
System.out.println("Second search request fail!");
}
SearchResponse secondResponse = secondItem.getResponse();
for (SearchHit documentFields : secondResponse.getHits().getHits()) {
System.out.println("Second search response: " + documentFields.getSourceAsString());
}
client.close();
} catch (Exception e) {
e.printStackTrace();
}
}

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :