在Elasticsearch中使用date_histogram聚合计算嵌套字段的总和

uemypmqf  于 2022-11-22  发布在  ElasticSearch
关注(0)|答案(2)|浏览(190)

我在使用date_histogram获取Elasticsearch中嵌套字段的总和时遇到了麻烦,我希望有人能帮我一把。
我有一个Map,看起来像这样:

"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处理嵌套字段的一个限制?
非常感谢您的帮助!
大卫

eblbsuwk

eblbsuwk1#

试试这个?

{
  "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”字段中。

lnvxswe2

lnvxswe22#

我在实现ES时试图解决类似问题时偶然发现了这个问题。
看起来Elasticsearch只关注JSON主体请求树中聚合的位置-而不是它的对象和字段的继承。所以你不应该把你的和聚合放在”date_histogram”里面,而是放在同一个JSON树的外面。
这对我很有效:

{
  "size": 0,
  "aggs": {
    "histogram_aggregation": {
      "date_histogram": {
        "field": "date_vield",
        "calendar_interval": "day"
      },
      "aggs": {
        "views": {
          "sum": {
            "field": "the_vield_i_want_to_sum"
          }
        }
      }
    }
  },
  "query": {
    #some query
    }

OP犯了一个错误,将其总和聚合放在日期直方图聚合内。

相关问题