RestAPI实现聚合

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
@Test
void testAggredation() throws IOException {
//1. 准备Request
SearchRequest request = new SearchRequest("hotel");
//2. 准备DSL
//2.1 设置size
request.source().size(0);
//2.2 聚合
request.source().aggregation(AggregationBuilders
.terms("brandAgg")
.field("brand")
.size(10)
);

//3. 发出请求
SearchResponse response = client.search(request,RequestOptions.DEFAULT);
//4. 解析结果
Aggregations aggregations = response.getAggregations();
//4.1 根据聚合名称获取聚合结果
Terms brandTerms = aggregations.get("brandAgg");
//4.2 获取buckets
List<? extends Terms.Bucket> buckets = brandTerms.getBuckets();
//4.3 遍历
for(Terms.Bucket bucket : buckets){
//4.4 获取key
String key = bucket.getKeyAsString();

System.out.println(key);
}


}

ps: