/** * 多字段分组并求和;实现sql:select field1, field2, sum(field3) from table_name group by field1, field2; */ public static void twiceAggSum(QueryBuilder query, String tableName, String groupField1, String groupField2, String sumField) { String group1_ = "group_" + groupField1; String group2_ = "group_" + groupField2; String sumField_ = "sum_" + sumField; //分组字段是id,排序由多个字段排序组成 TermsAggregationBuilder tb1 = AggregationBuilders.terms(group1_).field(groupField1); TermsAggregationBuilder tb2 = AggregationBuilders.terms(group2_).field(groupField2); tb2.order(Terms.Order.compound(Terms.Order.aggregation(sumField_, false))); SumAggregationBuilder sb = AggregationBuilders.sum(sumField_).field(sumField); tb2.subAggregation(sb); tb1.subAggregation(tb2); SearchRequestBuilder search = client.prepareSearch(tableName); if (query != null) { search.setQuery(query); } search.addAggregation(tb1); Terms userAgg = search.get().getAggregations().get(group1_); for (Terms.Bucket entry : userAgg.getBuckets()) { Terms sexAgg = entry.getAggregations().get(group2_); for (Terms.Bucket entry2 : sexAgg.getBuckets()) { Sum sum = entry2.getAggregations().get(sumField_); System.out.println("cityCode:" + entry.getKey() + " -------shopType:" + entry2.getKey() + " ----------sum:" + new BigDecimal(sum.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP).toPlainString()); } System.out.println(); } }