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());
}
}
}
正因为当初对未来做了太多的憧憬,所以对现在的自己尤其失望。生命中曾经有过的所有灿烂,终究都需要用寂寞来偿还。