@Test
public void testGroup() throws IOException {
SearchSourceBuilder builder = new SearchSourceBuilder ( );
BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery ( );
//聚合查询的过滤条件
queryBuilder.must ( QueryBuilders.termQuery ("age", "女") )
.filter (QueryBuilders.rangeQuery ("age").gte (18).lt (23));
//聚合查询 不查数据 所以这里设置0 根据实际需求来
builder.size (0);
builder.query (queryBuilder);
//聚合查询 terms自定义 field是想要分组的字段
TermsAggregationBuilder agr = AggregationBuilders.terms ("group_name").field ("grade").size (10);
//嵌套聚合查询
agr.subAggregation (AggregationBuilders.avg ("group_avg").field ("age"));
builder.aggregation (agr);
//创建查询请求
SearchRequest request = new SearchRequest ().indices ( "school" );
request.source (builder);
SearchResponse search = restHighLevelClient.search (request, RequestOptions.DEFAULT);
//通过自定义组名 获取结果
Terms terms = search.getAggregations ( ).get ("group_name");
for (Terms.Bucket bucket : terms.getBuckets ( )) {
Avg avg = bucket.getAggregations ( ).get ("group_avg");
/*
bucket.getAggregations ( ).get("....")的返回结果有很多种 根据自己的实际情况来定
1.如果用的是terms 则用Terms接收
2.如果用的avg 则用Avg对象进行接收
3.sum求和 则用Sum接收
...还有很多不依次举例了
如果是Terms对象 则在嵌套一层for循环进行取值 如果是其他聚合函数直接引用就ok
例如:
Terms terms2 = bucket.getAggregations ( ).get ("group_avg");
for (Terms.Bucket terms2Bucket : terms2.getBuckets ( )) {
terms2Bucket.getKey ( ).toString ( );
terms2Bucket.getDocCount ( );
}
*/
System.out.println ("班级名称:"+bucket.getKey ( ).toString ( )
+ " 妹纸数量:" + bucket.getDocCount ( )
+ " 妹纸平均年级:" + avg.getValue ( ));
}
}
API用的是 RestHighLevelClient类
本文转载自: https://blog.csdn.net/weixin_46981693/article/details/125092438
版权归原作者 LetItGo. 所有, 如有侵权,请联系我们删除。
版权归原作者 LetItGo. 所有, 如有侵权,请联系我们删除。