es 聚合查询 cardinality terms 对应java 解析代码

本文详细介绍了如何在Elasticsearch中使用Java进行aggregation查询,包括terms和top_hits聚合,并展示了如何处理cardinality语法。作者给出了相应的Java代码示例,涵盖了从构建查询到解析结果的过程。
摘要由CSDN通过智能技术生成

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();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值