ES 聚合-先group 在sum

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

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

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

public static void searchTest() throws IOException {
        TermsBuilder companyNameAgg = AggregationBuilders.terms("companyName").field("companyName").size(10);
        SumBuilder companyNameAggSum = AggregationBuilders.sum("companyNameSum").field("cvcount");
        companyNameAgg.subAggregation(companyNameAggSum);//把sum聚合器放入到Term聚合器中,相当于先group by在sum
        SearchRequestBuilder searchBuilder = ElasticClientFactory.getClient().prepareSearch(indexname).setTypes(typeName).addAggregation(companyNameAgg);
        SearchResponse searchResponse = searchBuilder.execute().actionGet();
        Terms terms = searchResponse.getAggregations().get("companyName");
        List<Terms.Bucket> buckets = terms.getBuckets();
        List<String> list = Lists.newArrayList();
        for (Terms.Bucket bucket : buckets) {
            InternalSum internalSum = bucket.getAggregations().get("companyNameSum");//注意从bucket而不是searchResponse
            System.out.println(bucket.getKeyAsString() + "\t" + bucket.getDocCount() + "\t"+internalSum.getValue());
        }
        System.out.println("done");
    }
原文链接:https://www.f2er.com/javaschema/283226.html

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