JAVA Rest High Level Client如何取聚合後得數據

對於剛剛學習es的童鞋來講,很容易不清楚怎麼獲取客戶端對es文檔的聚合結果,下面就演示一下模仿DSL寫聚合,而後獲取到聚合的結果。java

一, 對於下面這個簡單的聚合,目的是對於文檔全文匹配,聚合顏色字段。把知足匹配的文檔放入自定義名稱的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調用,那麼解析過程徹底能夠複用。api

相關文章
相關標籤/搜索