erpGoodsId、batchNum 和 wmsProductCode 三个字段分组后,怎么获取所有分组的总数
时间: 2024-03-20 20:43:45 浏览: 38
两种方法实现mysql分组计数,范围汇总
在 Elasticsearch 的聚合语句中,可以使用 `cardinality` 聚合来计算某个字段的去重值个数,从而得到分组的总数。具体的做法是,在 `composite` 聚合的外层,再套一层 `cardinality` 聚合,如下所示:
```
{
"query": {
"bool": {
"should": [
{
"match": {
"erpSupplierFlowId": "1001E111230001IPJP6W"
}
},
{
"match": {
"erpSupplierFlowId": "1001A110000001CBWJ0I"
}
},
{
"match": {
"erpSupplierFlowId": "1001A110000001IPM06S"
}
},
{
"match": {
"companyCode": "10101"
}
}
]
}
},
"size": 0,
"track_total_hits": false,
"aggs": {
"my_buckets": {
"composite": {
"size": 1000,
"sources": [
{
"erpGoodsId": {
"terms": {
"field": "erpGoodsId",
"order": "asc"
}
}
},
{
"batchNum": {
"terms": {
"field": "batchNum",
"order": "asc"
}
}
},
{
"wmsProductCode": {
"terms": {
"field": "wmsProductCode",
"missing": "null",
"order": "asc"
}
}
}
]
},
"aggs": {
"filter_empty_dest": {
"bucket_selector": {
"buckets_path": {
"count": "_count"
},
"script": "params.count != null"
}
}
}
},
"total_groups": {
"cardinality": {
"fields": [
"erpGoodsId",
"batchNum",
"wmsProductCode"
]
}
}
}
}
```
在聚合结果中,`total_groups` 聚合的 `value` 字段即为分组的总数。
阅读全文