【问题标题】:How to do a year over year aggregation with Elasticsearch?如何使用 Elasticsearch 进行年度聚合?
【发布时间】:2020-04-11 02:56:08
【问题描述】:

假设我在文档上有一个日期字段,我知道使用 date_histogram 聚合可以按天、月、年等获取文档计数。

我想做的是获取给定年份中 1 月、2 月、3 月等的平均文档数量。在给定的几周内,周一、周二、周三等也是如此。有没有办法使用相同的日期字段来做到这一点,或者使用 Elasticsearch 实现这一目标的最佳方法是什么?


示例

假设我们有一堆超过三年的订单:

  • 2012 - 1 月(10 个订单)、2 月(5 个订单)、3 月(7 个订单)、4 月(11 个订单)等
  • 2013 - 1 月(13 个订单)、2 月(7 个订单)、3 月(12 个订单)、4 月(15 个订单)等
  • 2014 - 1 月(10 个订单)、2 月(7 个订单)、3 月(6 个订单)、4 月(13 个订单)等。

我想要的是给定年份每个月的平均值,因此输出将是:

1 月(10 + 13 + 10 / 3 = 11 个订单)、2 月(6.33 个订单)、3 月(8.33 个订单)、4 月(13 个订单)等

最好能将其推广到 N 年(或 N 个一月等),以便我们在任何日期范围内进行搜索。

【问题讨论】:

    标签: elasticsearch


    【解决方案1】:

    您可以像这样使用“monthOfYear”:

    "aggregations": {
        "timeslice": {
            "histogram": {
                "script": "doc['timestamp'].date.getMonthOfYear()",
                "interval": 1,
                "min_doc_count": 0,
                "extended_bounds": {
                    "min": 1,
                    "max": 12
                },
                "order": {
                    "_key": "desc"
                }
            }
        }
    

    扩展的界限将确保您获得每个月的值(即使它为零)。

    如果您想要月份名称,您可以在自己的代码中执行此操作,或者执行此操作(结果是您将无法获得没有数据的月份的值):

    "aggregations": {
        "monthOfYear": {
            "terms": {
                "script": "doc['timestamp'].date.monthOfYear().getAsText()",
                "order": {
                    "_term": "asc"
                }
            }
        }
    

    一旦你有了这个,你就可以将你的统计聚合嵌套在这个里面:

    "aggregations: {
        "monthOfYear": {
            "terms": {
                ...
            },
            "aggregations": {
                "stats": ...
            }
        }
     }
    

    这个问题现在已经很老了,但是,希望这对某人有所帮助。

    【讨论】:

      【解决方案2】:

      我对你想要的理解是:

      您希望查看每年存储桶中每月的平均文档数

      对吗?

      如果是这样,您可以计算一年中的文档数量(即年度存储桶),然后使用脚本除以 12。

      例如在每周存储桶中显示每日平均文档计数(假设每月 30 天):

      curl -XGET 'http://localhost:9200/index/type/_search?pretty' -d '{
        "aggs" : {
          "monthly_bucket": {
               "date_histogram": {"field": "datefield","interval": "week"},
                    "aggs" : {
                          "weekly_average": {"sum" : {"script" : " doc[\"datefield\"].value>0 ? 1/30 : 0"} }}
               }
           }
      }'
      

      【讨论】:

      • 这不是我想要的(尽管使用脚本可能仍然是我需要的......我会调查的)。我用一个例子更新了我的问题,以更好地解释我所追求的。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-20
      • 2014-09-18
      • 1970-01-01
      • 2020-12-19
      • 1970-01-01
      • 2016-02-17
      相关资源
      最近更新 更多