11月 07 RestClient-多条件聚合 Elasticsearch,java 在对应的service层里面写: HotelService里的代码如下: 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071@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) ); } 上一篇 自动补全 & (自定义)拼音分词器 & 搜索时注意事项 下一篇 RestAPI实现聚合