我正在尝试获取聚合总数大于某个数量(比如 1000)的记录。以下是文档样本。
[
{
"_index": "orders_stage",
"_type": "order",
"_id": "AV3FtHR8lArSPNJl_rcp",
"_score": 1,
"_source": {
"total_amount": 650,
"custid": "2",
"client_id": 1
}
},
{
"_index": "orders_stage",
"_type": "order",
"_id": "AV3F5UfjlArSPNJl_rlu",
"_score": 1,
"_source": {
"total_amount": 200,
"custid": "1",
"client_id": 1
}
},
{
"_index": "orders_stage",
"_type": "order",
"_id": "AV3F5UfjlArSPNJl_rxm",
"_score": 1,
"_source": {
"total_amount": 1400,
"custid": "1",
"client_id": 1
}
}
]
所以首先,我使用 custid 对记录进行分组(聚合),然后我想要那些 total_amount 的总和大于某个数量(比如 1000)的记录。我尝试了以下查询:
{
"query": {
"bool": {
"must": [
{
"term": {
"client_id": 1
}
},
{
"range": {
"amount_spent": {
"gte": 1000
}
}
}
]
}
},
"aggs": {
"customers": {
"terms": {
"field": "custid"
},
"aggs": {
"amount_spent": {
"sum": {
"field": "total_amount"
}
}
}
}
}
}
当我运行这个查询时,我没有得到任何东西,有人可以指导我过滤聚合结果吗。
谢谢
最佳答案
您需要使用 bucket_selector
pipeline aggregation ,你不能在查询部分这样做:
{
"query": {
"bool": {
"must": [
{
"term": {
"client_id": 1
}
}
]
}
},
"aggs": {
"customers": {
"terms": {
"field": "custid"
},
"aggs": {
"amount_spent": {
"sum": {
"field": "total_amount"
}
},
"amount_spent_filter": {
"bucket_selector": {
"buckets_path": {
"amountSpent": "amount_spent"
},
"script": "params.amountSpent > 1000"
}
}
}
}
}
}
关于sql - elasticsearch - 总金额的总和大于使用聚合的某个金额,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45791253/