public Map<String, Map<String, Long>> aggTwoArgs(String indices, QueryBuilder queryBuilder, String args1, String args2, int i) throws IOException {
Map<String, Map<String, Long>> map = new HashMap<>();
//设置要查询的索引
SearchRequest request = new SearchRequest().indices(indices);
//构建搜索
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//添加搜索长度
sourceBuilder.size(0);
//添加搜索条件
sourceBuilder.query(queryBuilder);
//设置要聚合的字段以及条数
//设置该次聚合的名称 terms(args1)
//以及要聚合的字段field(args1 + ".keyword") 添加keyword是对字段进行不分词查询。
TermsAggregationBuilder agg1 = AggregationBuilders.terms(args1).field(args1 + ".keyword").size(i);
//设置子聚合以及条数,设置返回数据中该聚合的名称 terms(args2),以及要聚合的字段field(args2 + ".keyword")
TermsAggregationBuilder agg2 = AggregationBuilders.terms(args2).field(args2 + ".keyword").size(i);
//合并子聚合
agg1.subAggregation(agg2);
//添加聚合查询
sourceBuilder.aggregation(agg1);
//创建请求
request.source(sourceBuilder);
//发送请求
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
Aggregations aggregations = response.getAggregations();
Terms terms1 = aggregations.get(args1);
for (Terms.Bucket bucket1 : terms1.getBuckets()) {
Terms terms2 = bucket1.getAggregations().get(args2);
Map<String, Long> map1 = new HashMap<>();
for (Terms.Bucket bucket2 : terms2.getBuckets()) {
map1.put(bucket2.getKeyAsString(), bucket2.getDocCount());
}
map.put(bucket1.getKeyAsString(), map1);
}
return map;
}
Java代码实现es的聚合查询
最新推荐文章于 2024-10-12 08:54:04 发布
关键词由优快云通过智能技术生成