javaAPI操作ES分组聚合

连接es的客户端使用的 TransportClient

 

SearchRequestBuilder requestBuilder = transportClient.prepareSearch(indies).setTypes(TYPE_NAME);
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
AggregationBuilder groupByType = AggregationBuilders.terms("分组别名").field("分组字段");
AggregationBuilder sumDownOutputSum = AggregationBuilders.sum("聚合别名").field("聚合字段");
  //sub是子聚合
requestBuilder.setQuery(boolQueryBuilder).addAggregation(groupByType.subAggregation(sumDownOutputSum));

SearchResponse response = requestBuilder.get();
Terms terms = response.getAggregations().get("groupByType");

for (Terms.Bucket bucket : terms.getBuckets()) {
Map<String, Object> resMap = new HashMap<>();
Sum downOutputSum = bucket.getAggregations().get("downOutputSum");
double value = downOutputSum.getValue();
Object key = bucket.getKey();
//key 是分组字段
  //value是聚合value  

}
上一篇:4.集群、JavaAPI


下一篇:03-JAVAAPI-Synchronized原理