Histogram over fixed range of dates (i.e. fixed number of buckets) even when data is absent

谁都会走 提交于 2021-01-28 22:42:11

问题


My goal is to build a histogram between a start and an end dates, the empty dates should appear in the histogram and have zero as a count value.

I am trying the following query to fetch the last 7 days:

POST my_index/_search
{
  "size": 0,
  "query": {
    "range": {
      "date": {
        "gte": "now-7d/d",
        "lte": "now/d"
        }
      }
  },
  "aggs" : {
      "count_per_day" : {
          "date_histogram" : {
              "field" : "date",
              "interval" : "day",
              "order": {"_key": "desc"},
              "min_doc_count": 0
          }
      }
  }
}

The issues is that I have data only for the last 3 days, so there is no data at all prior to 3 days ago. In this case, the result contains only the last 3 days and the previous days are not returned at all.

But if there is a gap (i.e. there is data 6 days ago, but no data in the 5th and the 4th day), the empty days will appear with zero as a count.

How can I force to return the absent dates even if there is no data? In other word, how to fix the number of buckets (to 7 in the example above) even if there is no data?


回答1:


You have already added "min_doc_count": 0 to include empty buckets. All you need to do is to simply add extended_bounds param as well to force starting and ending buckets. More on it can be found here.

Update your query as below:

{
  "size": 0,
  "query": {
    "range": {
      "date": {
        "gte": "now-7d/d",
        "lte": "now/d"
      }
    }
  },
  "aggs": {
    "count_per_day": {
      "date_histogram": {
        "field": "date",
        "interval": "day",
        "order": {
          "_key": "desc"
        },
        "min_doc_count": 0,
        "extended_bounds": {
          "min": "now-7d/d",
          "max": "now/d"
        }
      }
    }
  }
}


来源:https://stackoverflow.com/questions/54942602/histogram-over-fixed-range-of-dates-i-e-fixed-number-of-buckets-even-when-dat

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!