ES 聚合-先group 在sum

前端之家收集整理的这篇文章主要介绍了ES 聚合-先group 在sum前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

实现一个sql: SELECT sum(field) from table group by field2

使用:AggregationBuilders.sum("name").field("field");

  1. public static void searchTest() throws IOException {
  2. TermsBuilder companyNameAgg = AggregationBuilders.terms("companyName").field("companyName").size(10);
  3. SumBuilder companyNameAggSum = AggregationBuilders.sum("companyNameSum").field("cvcount");
  4. companyNameAgg.subAggregation(companyNameAggSum);//把sum聚合器放入到Term聚合器中,相当于先group by在sum
  5. SearchRequestBuilder searchBuilder = ElasticClientFactory.getClient().prepareSearch(indexname).setTypes(typeName).addAggregation(companyNameAgg);
  6. SearchResponse searchResponse = searchBuilder.execute().actionGet();
  7. Terms terms = searchResponse.getAggregations().get("companyName");
  8. List<Terms.Bucket> buckets = terms.getBuckets();
  9. List<String> list = Lists.newArrayList();
  10. for (Terms.Bucket bucket : buckets) {
  11. InternalSum internalSum = bucket.getAggregations().get("companyNameSum");//注意从bucket而不是searchResponse
  12. System.out.println(bucket.getKeyAsString() + "\t" + bucket.getDocCount() + "\t"+internalSum.getValue());
  13. }
  14. System.out.println("done");
  15. }

猜你在找的设计模式相关文章