【问题标题】:How to group by month in Elastic search如何在弹性搜索中按月分组
【发布时间】:2019-01-23 03:22:30
【问题描述】:

我使用的是弹性搜索版本 6.0.0 对于按月分组,我使用日期直方图聚合。 我试过的例子:

{  
   "from":0,
   "size":2000,
   "_source":{  
      "includes":[  
         "cost",
         "date"
      ],
      "excludes":[  

      ],
      "aggregations":{  
         "date_hist_agg":{  
            "date_histogram":{  
               "field":"date",
               "interval":"month",
               "format":"M",
               "order":{  
                  "_key":"asc"
               },
               "min_doc_count":1
            },
            "aggregations":{  
               "cost":{  
                  "sum":{  
                     "field":"cost"
                  }
               }
            }
         }
      }
   }
}

结果我多次获得 1(1 月/1 月)。 因为我有 2016 年 1 月、2017 年 1 月、2018 年 1 月的数据,所以会在一月返回 3 次。但我只想要一月一次,其中包含一月所有年份的总和。

【问题讨论】:

    标签: elasticsearch elasticsearch-5 elasticsearch-aggregation elasticsearch-6


    【解决方案1】:

    除了使用date_histogram 聚合之外,您还可以将terms 聚合与从日期中提取月份的脚本一起使用。

    {
      "from": 0,
      "size": 2000,
      "_source": {"includes": ["cost","date"],"excludes"[]},
      "aggregations": {
        "date_hist_agg": {
          "terms": {
            "script": "doc['date'].date.monthOfYear",
            "order": {
              "_key": "asc"
            },
            "min_doc_count": 1
          },
          "aggregations": {
            "cost": {
              "sum": {
                "field": "cost"
              }
            }
          }
        }
      }
    }
    

    请注意,使用脚本并非最佳选择,如果您知道需要月份信息,只需使用该信息创建另一个字段,这样您就可以在其上使用简单的术语聚合,而无需使用脚本。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-07
    • 1970-01-01
    • 2023-03-03
    • 2019-02-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多