实现一个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");
- }