es 查询语法 agga 查询
例如 es 的 categories 擦查询语法
{
"size": 0,
"aggregations": {
"firstAggregations": {
"terms": {
"field": "user_id",
"size": 50,
"min_doc_count": 1,
"shard_min_doc_count": 0,
"show_term_doc_count_error": false,
"order": [{
"_count": "desc"
}, {
"_key": "asc"
}]
},
"aggregations": {
"secondAggregations": {
"top_hits": {
"from": 0,
"size": 1,
"version": false,
"seq_no_primary_term": false,
"explain": false,
"sort": [{
"publish_time": {
"order": "desc"
}
}]
}
}
}
}
}
}
对应jiava 代码组装 和解析数据
//1. firstAggregations聚合
TermsAggregationBuilder firstAggregations= AggregationBuilders.terms("firstAggregations").field("user_id").order(BucketOrder.count(false)).size(100);
//2. secondAggregations排序
firstAggregations.subAggregation(AggregationBuilders.topHits("secondAggregations").size(1).sort("publish_time", SortOrder.DESC));
//3. 结果部分代码
Aggregations aggregations = searchResponse.getAggregations();
//4. firstAggregations 用terms聚合,结果使用Terms类接收
Terms firstAggregations = aggregations.get("firstAggregations");
List<? extends Terms.Bucket> bucketList = firstAggregations.getBuckets();
List<Map<String,Object>> voList = bucketList.stream()
.map(bucket -> {
Aggregations bucketAggregations = bucket.getAggregations();
//5. secondAggregations使用top_hits聚合,结果使用TopHits类接收
TopHits secondAggregations = bucketAggregations.get("secondAggregations");
SearchHits searchHits = secondAggregations.getHits();
SearchHit[] hits = searchHits.getHits();
SearchHit hit = hits[0];
return hit.getSourceAsMap();
}).collect(Collectors.toList());
2 如果包含 cardinality 语法
{
"size": 0,
"aggregations": {
"unique_categories_count": {
"cardinality": {
"field": "sellerId"
}
}
}
}
}
对应的 java 解析代码
Aggregations aggregations = searchResponse.getAggregations();
Cardinality cardinality= aggregations.get("unique_categories_count");
int count = (int) cardinality.getValue();