酒店数据全文检索练习(4)-数据聚合,过滤条件
前言
前面学习了数据的聚合功能,现在我们把他用到酒店数据全文检索的项目中来,实现条件过滤的动态展示,之前条件过滤都是写死在前端的,并不会随着搜索结果进行动态展示,这就导致了一个问题,例如:某个酒店只有上海有,但是城市中还是有北京,深圳,当我再去点深圳的时候就搜不到结果了。这一节,我们就通过es的聚合查询,来实现过滤条件的动态展示
代码实现
因为fifters方法与查询方法搜索条件一样,所以可以复用之前的查询对象
HotelService新增方法
@Override
public Map<String, List<String>> filters(RequestParams requestParams) {
SearchRequest request = new SearchRequest("hotel");
//构建BooleanQuery
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
//构建查询语句
buildBasicQuery(requestParams, boolQuery);
request.source().size(0);
request.source().aggregation(AggregationBuilders.terms("cityAgg").field("city").size(100));
request.source().aggregation(AggregationBuilders.terms("starNameAgg").field("starName").size(100));
request.source().aggregation(AggregationBuilders.terms("brandAgg").field("brand").size(100));
request.source().query(boolQuery);
Map<String, List<String>> resultMap = new HashMap<>();
try {
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
List<String> cityList = getAggList(response, "cityAgg");
List<String> starNameList = getAggList(response, "starNameAgg");
List<String> brandList = getAggList(response, "brandAgg");
resultMap.put("city", cityList);
resultMap.put("starName", starNameList);
resultMap.put("brand", brandList);
return resultMap;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private List<String> getAggList(SearchResponse response, String addName) {
List<String> aggList = new ArrayList<>();
Terms cityAgg = response.getAggregations().get(addName);
List<? extends Terms.Bucket> buckets = cityAgg.getBuckets();
for (Terms.Bucket bucket : buckets) {
aggList.add(bucket.getKeyAsString());
}
return aggList;
}
HotelController新增方法
@PostMapping("/filters")
public Map<String, List<String>> filters(@RequestBody RequestParams requestParams){
return hotelService.filters(requestParams);
}
查看效果
上海时,结果由于只有上海,条件过滤里就没有其他城市了,符合我们的要求~
酒店数据全文检索练习(4)-数据聚合,过滤条件
https://www.zhaojun.inkhttps://www.zhaojun.ink/archives/1015