elasticsearch - 总金额的总和大于使用聚合的某个金额

elasticsearch - sum of total amount is greater than some amount using aggregation

我正在尝试获取聚合总数大于某个数量(比如 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"
          }
        }
      }
    }
  }
}