JAVA Rest High Level Client如何取聚合后的数据

对于刚刚学习es的童鞋来说,很容易不清楚怎么获取客户端对es文档的聚合结果,下面就演示一下模仿DSL写聚合,然后获取到聚合的结果。

一, 对于下面这个简单的聚合,目的是对于文档全文匹配,聚合颜色字段。把满足匹配的文档放入自定义名称的colors桶中,参照《elasticsearch权威指南》的范围限定聚合

 1 {
 2     "size" : 0,
 3     "query" : {
 4         "match_all" : {}
 5     },
 6     "aggs" : {
 7         "colors" : {
 8             "terms" : {
 9               "field" : "color"
10             }
11         }
12     }
13 }

二, 对照着这个DSL写我们的java rest client api的调用方法,供业务层调用

 1     /**
 2      * ES中查询所有color
 3      *
 4      * @param indices
 5      * @return
 6      */
 7     public SearchResponse getAllColor(String... indices) {
 8         SearchRequest searchRequest = new SearchRequest(indices);
 9         SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder().size(0);
10         searchSourceBuilder.query(QueryBuilders.matchAllQuery());
11         TermsAggregationBuilder builder = AggregationBuilders.terms("colors").field("color");
12         searchSourceBuilder.aggregation(builder);
13         searchRequest.source(searchSourceBuilder);
14 
15         try {
16             return client.getHighLevelClient().search(searchRequest);
17         } catch (IOException e) {
18             throw new BizException("聚合失败:{}", e.getCause());
19         }
20     }

三, 在我们的业务层调用上文中的getAllColor方法获取response,对response解析,获取聚合的结果

 2      * 颜色信息
 3      *
 4      * @return
 5      */
 6     public List<String> getAllColorInfo() {
 7         SearchResponse response = highRestHelper.getAllColor(getIndices());
 8         Aggregations aggregations = response.getAggregations();
 9         ParsedStringTerms colorTerms = aggregations.get("app_group");
10         List<String> colors = new ArrayList<>();
11         List<? extends Terms.Bucket> buckets = colorTerms.getBuckets();
12         for (Terms.Bucket bucket : buckets) {
13             String appName = bucket.getKey().toString();
14             colors.add(appName);
15         }   
16         return colors;
17     } 

至此即可获取所有的聚合结果,只要能够参照DSL,转换成相应的api调用,那么解析过程完全可以复用。

posted @ 2019-11-13 11:09  x1aoda1  阅读(5936)  评论(0编辑  收藏  举报