即使没有数据,在固定日期范围内(即固定数量的存储桶)的直方图 [英] Histogram over fixed range of dates (i.e. fixed number of buckets) even when data is absent
问题描述
我的目标是在开始日期和结束日期之间建立直方图,空日期应显示在直方图中,并且计数值为零.
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.
我正在尝试以下查询以获取最近7天:
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
}
}
}
}
问题在于我只有最近3天的数据,因此3天之前没有任何数据.在这种情况下,结果仅包含最近3天,而前几天完全不返回.
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.
但是,如果存在差距(即6天前有数据,但第5天和第4天没有数据),则空天将以零作为计数出现.
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.
即使没有数据,如何强制返回缺席日期?换句话说,即使没有数据,如何确定存储桶的数量(在上面的示例中为7)?
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?
推荐答案
您已经添加了"min_doc_count":0
以包含空存储桶.您需要做的就是简单地添加 extended_bounds
参数以及强制开始和结束存储桶.可以在
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.
如下更新查询:
{
"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"
}
}
}
}
}
这篇关于即使没有数据,在固定日期范围内(即固定数量的存储桶)的直方图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!