首页 > 解决方案 > 使用弹性搜索版本:6.4.3。我想按一个字段(类型是日期)分组,几天之间有一个小时

问题描述

我想按 start_time 分组,小时在 20190701 和 20190710 之间,但不是每天每个小时都是一个桶,我希望将数据分成 24 个桶,例如:20190701,20190801,20190901...落入 01 桶,20190702 ,20190802,20190902...落入02桶等等。

这是每天每个小时都是一个桶,结果不是我想要的,如何解决这个问题?

start_time 字段类型如下:

"start_time": 
{
      "type": "date",
       "format": "yyyy-MM-dd HH:mm:ss||epoch_second"
}

我的代码如下:

GET qd_analysis/kw/_search
{
  "size": 0, 
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "uin":   {
              "value": "111"
            }
          }
        },
        {
          "range": {
            "imp_date": {
              "gte": "20190701",
              "lte": "20190710"
            }
          }
        }
      ]
    }
  },
  "aggs": {
    "result": {
      "date_histogram": {
        "field": "start_time",
        "time_zone": "+08:00",
        "interval": "hour",
        "format": "HH",
        "order": {
          "_count": "desc"
        }
      }
    }
  }
}

我想按 start_time 分组,小时在 20190701 和 20190710 之间,但不是每天每个小时都是一个桶,我希望将数据分成 24 个桶,例如:20190701,20190801,20190901...落入 01 桶,20190702 ,20190802,20190902...落入02桶等等。

标签: elasticsearch-aggregation

解决方案


您将需要使用术语聚合和脚本来提取一天中的时间:

{
  "aggs": {
     "hour_of_day": {
        "terms": {
           "script": "doc['@timestamp'].date.hourOfDay"
         }
      }
   }
}

推荐阅读