RestClient-多条件聚合

在对应的service层里面写:

HotelService里的代码如下:

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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
@Override
public Map<String, List<String>> filters() {

try {
//1. 准备Request
SearchRequest request = new SearchRequest("hotel");
//2. 准备DSL
//2.1 设置size
request.source().size(0);
//2.2 聚合
buildAggretgaion(request);

//3. 发出请求
SearchResponse response = client.search(request,RequestOptions.DEFAULT);

//4. 解析结果
Map<String,List<String>> result = new HashMap<String, List<String>>();
Aggregations aggregations = response.getAggregations();
//4.1 根据品牌(聚合名称)名称获取品牌的结果
List<String> brandList = getAddByName(aggregations,"brandAgg");
result.put("品牌",brandList); //放入map
//4.2 根据城市(聚合名称)名称获取品牌的结果
List<String> cityList = getAddByName(aggregations,"cityList");
result.put("城市",cityList); //放入map
//4.3 根据星级(聚合名称)名称获取品牌的结果
List<String> starList = getAddByName(aggregations,"starList");
result.put("星级",starList); //放入map

return result;

} catch (IOException e) {
throw new RuntimeException();
}
}

//(抽取出来的) 根据名称获取品牌的结果
private List<String> getAddByName(Aggregations aggregations, String aggName) {
//4.1 根据聚合名称获取聚合结果
Terms brandTerms = aggregations.get(aggName);
//4.2 获取buckets
List<? extends Terms.Bucket> buckets = brandTerms.getBuckets();
//4.3 遍历
List<String> brandList = new ArrayList<String>();
for(Terms.Bucket bucket : buckets){
//4.4 获取key
String key = bucket.getKeyAsString();
brandList.add(key);

System.out.println(key);
}
return brandList;
}

//抽取出来的 聚合
private void buildAggretgaion(SearchRequest request) {
request.source().aggregation(AggregationBuilders
.terms("brandAgg")
.field("brand")
.size(10)
);
request.source().aggregation(AggregationBuilders
.terms("cityAgg")
.field("city")
.size(10)
);
request.source().aggregation(AggregationBuilders
.terms("starAgg")
.field("starName.keyword")
.size(10)
);
}