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

时间:2017-08-21 07:14:12

标签: sql elasticsearch group-by kibana

我正在尝试获取我的聚合总数大于某个数量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对记录进行分组(agg),然后我想要那些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"
          }
        }
      }
    }
  }
}

当我运行此查询时,我没有得到任何内容,有人可以指导我过滤聚合结果。

由于

1 个答案:

答案 0 :(得分:3)

您需要使用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"
          }
        }
      }
    }
  }
}