【问题标题】:Calculating sum of nested fields with date_histogram aggregation in Elasticsearch在 Elasticsearch 中使用 date_histogram 聚合计算嵌套字段的总和
【发布时间】:2014-06-14 12:43:19
【问题描述】:

我无法使用 date_histogram 在 Elasticsearch 中获取嵌套字段的总和,我希望有人能帮帮我。

我有一个如下所示的映射:

"client" : {
  // various irrelevant stuff here...

  "associated_transactions" : {
    "type" : "nested",
    "include_in_parent" : true,
    "properties" : {
      "amount" : {
        "type" : "double"
      },
      "effective_at" : {
        "type" : "date",
        "format" : "dateOptionalTime"
      }
    }
  }
}

我正在尝试获取一个 date_histogram,显示所有客户按月显示的总收入——即在由 associated_transactions.effective_date 确定的直方图中显示总和 associated_transactions.amount 的时间序列。我尝试运行此查询:

{
  "query": {
    // ...
  },
  "aggregations": {
    "revenue": {
      "date_histogram": {
        "interval": "month",
        "min_doc_count": 0,
        "field": "associated_transactions.effective_at"
      },
      "aggs": {
        "monthly_revenue": {
          "sum": {
            "field": "associated_transactions.amount"
          }
        }
      }
    }
  }
}

但它给我的金额不对。似乎 ES 正在做的是查找在给定月份有任何交易的所有客户,然后对这些客户的所有交易(从任何时间)求和。也就是说,它是在给定月份进行购买的客户在其生命周期中花费的总和,而不是在给定月份的购买总和。

有什么方法可以获取我正在寻找的数据,或者这是 ES 如何处理嵌套字段的限制?

非常感谢您的帮助!

大卫

【问题讨论】:

    标签: elasticsearch


    【解决方案1】:

    试试这个?

    {
      "query": {
        // ...
      },
      "aggregations": {
        "revenue": {
          "date_histogram": {
            "interval": "month",
            "min_doc_count": 0,
            "field": "associated_transactions.effective_at"
    
            "aggs": {
              "monthly_revenue": {
                "sum": {
                  "field": "associated_transactions.amount"
                }
              }
            }
          }
        }
      }
    }
    

    即将“aggs”键移动到“date_histogram”字段中。

    【讨论】:

      猜你喜欢
      • 2015-07-30
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      • 1970-01-01
      • 2017-09-13
      • 2018-06-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多