/**
     * 多字段分组并求和;实现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();
        }
    }
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐