對於剛剛學習es的童鞋來講,很容易不清楚怎麼獲取客戶端對es文檔的聚合結果,下面就演示一下模仿DSL寫聚合,而後獲取到聚合的結果。java
1 { 2 "size" : 0, 3 "query" : { 4 "match_all" : {} 5 }, 6 "aggs" : { 7 "colors" : { 8 "terms" : { 9 "field" : "color" 10 } 11 } 12 } 13 }
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 }
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