/** * 多字段分组并求和;实现sql:select field1, field2, sum(field3) from table_name group by field1, field2; */ public static void twiceAggCount(QueryBuilder query, String tableName, String groupField1, String groupField2) { String group1_ = "group_" + groupField1; String group2_ = "group_" + groupField2; TermsAggregationBuilder tb1 = AggregationBuilders.terms(group1_).field(groupField1); TermsAggregationBuilder tb2 = AggregationBuilders.terms(group2_).field(groupField2); tb1.subAggregation(tb2); SearchRequestBuilder searchRequestBuilder = client.prepareSearch(tableName); SearchResponse searchResponse = searchRequestBuilder.addAggregation(tb1).setQuery(query).execute().actionGet(); Map<String, Aggregation> aggMap = searchResponse.getAggregations().asMap(); StringTerms gradeTerms = (StringTerms) aggMap.get(group1_); Iterator<StringTerms.Bucket> iterator = gradeTerms.getBuckets().iterator(); while (iterator.hasNext()) { StringTerms.Bucket gradeBucket = iterator.next(); // System.out.println(gradeBucket.getKey() + "年级有" + gradeBucket.getDocCount() + "个学生。"); StringTerms classTerms = (StringTerms) gradeBucket.getAggregations().asMap().get(group2_); Iterator<StringTerms.Bucket> classBucketIt = classTerms.getBuckets().iterator(); while (classBucketIt.hasNext()) { StringTerms.Bucket classBucket = classBucketIt.next(); System.out.println("cityCode:" + gradeBucket.getKey() + " -------shopType:" + classBucket.getKey() + " ----------sum:" + classBucket.getDocCount()); } System.out.println(); } }