GET es-index/_search
{
"size": 0,
"aggs": {
"group_by_data_domain": {
"terms": {
"field": "data.domain.keyword"
},
"aggs": {
"count_domain": {
"bucket_selector": {
"buckets_path": {
"domain_count": "_count"
},
"script": {
"source": "params.domain_count >=1 "
}
}
}
}
}
}
}
java代码实现参考
String tremsAlias = "userIdGroup";
//先分组,如果不指定size,默认10条,这里可以传个int最大值 2147483647,一次取所有数据
TermsAggregationBuilder termsAgg = AggregationBuilders.terms(tremsAlias).field("userId").size(Integer.MAX_VALUE).order(Terms.Order.term(true));
//聚合,count为自带的
termsAgg.subAggregation(AggregationBuilders.avg("avgAmount").field("amount"));
//声明BucketPath,用于后面的bucket筛选
Map<String, String> bucketsPathsMap = new HashMap<>(8);
bucketsPathsMap.put("orderCount", "_count");
bucketsPathsMap.put("avgAmount", "avgAmount");
//设置脚本
Script script = new Script("params.avgAmount >= 100 && params.orderCount >=2");
//构建bucket选择器
BucketSelectorPipelineAggregationBuilder bs =
PipelineAggregatorBuilders.bucketSelector("having", bucketsPathsMap, script);
termsAgg.subAggregation(bs);
SearchRequestBuilder sb = client.prepareSearch("index_test").setTypes("type_order");
SearchResponse sr = sb.setSize(0).addAggregation(termsAgg).execute().actionGet();
System.out.println("查询Query:");
System.out.println(sb);
//获取聚合筛选的结果数据
LongTerms lt = sr.getAggregations().get(tremsAlias);
List<LongTerms.Bucket> buckets = lt.getBuckets();
for (int i = 0; i < buckets.size(); i++) {
LongTerms.Bucket bucket = buckets.get(i);
System.out.println("-------------------------");
System.out.println(bucket.getKey());
System.out.println("count = " + bucket.getDocCount());
List<Aggregation> list = bucket.getAggregations().asList();
for (Aggregation agg : list) {
if (agg instanceof InternalAvg) {
InternalAvg ia = bucket.getAggregations().get("avgAmount");
System.out.println("avgAmount = " + ia.getValue());
}
}
System.out.println("-------------------------");
}
————————————————
版权声明:本文为CSDN博主「五只鸭子」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/tuposky/article/details/81002526
文章评论