ES 分组排序java实现

多字段分组并求和;实现sql:select field1, field2, sum(field3) from table_name group by field1, field2;

多字段分组并求和;实现sql:select field1, field2, top(field3) from table_name group by field1, field2;

ES java 样例:

/**
     * 多字段分组并求和;实现sql:select field1, field2, sum(field3) from table_name group by field1, field2;
     */
    @Test
    public void sumAfterTwiceAgg() {
        SearchResponse response = client.prepareSearch("test_index").setTypes("tweet")
                .addAggregation(AggregationBuilders.terms("userAgg").field("user.keyword")
                        .subAggregation(AggregationBuilders.terms("sexAgg").field("sex.keyword")
                                .subAggregation(AggregationBuilders.sum("sumAgg").field("age"))))  //求和要放到最内层的分组语句里面

                .get();
        Terms userAgg = response.getAggregations().get("userAgg");
        for (Terms.Bucket entry : userAgg.getBuckets()) {
            Terms sexAgg = entry.getAggregations().get("sexAgg");
            for (Terms.Bucket entry2 : sexAgg.getBuckets()) {
                Sum sum = entry2.getAggregations().get("sumAgg");
                System.out.println("user:" + entry.getKey()+"-------sex:"+entry2.getKey() + "----------sum:" + sum.getValue());
            }
        }
    }

 

posted @ 2019-05-10 09:56  柚子=_=  阅读(3593)  评论(0编辑  收藏  举报