按天聚合时如何计算空桶数?
How to calculate the number of empty bucket when aggregating by days?
我想得到一个人五月份在一个城镇停留的天数(Month
等于5)。
这是我的查询,但它为我提供了 myindex
中 PersonID
等于 111
且 Month
等于 5 的条目数。例如,此查询可能会给我类似 90 的输出,但每个月最多有 31 天。
GET myindex/_search?
{
"size":0,
"query": {
"bool": {
"must": [
{ "match": {
"PersonID": "111"
}},
{ "match": {
"Month": "5"
}}
]
} },
"aggs": {
"stay_days": {
"terms" : {
"field": "Month"
}
}
}
}
在 myindex
中,我有像 DateTime
这样的字段,其中包含某人通过相机注册的日期和时间,例如2017-05-01T00:30:08"
。所以,同一个人在一天中可能会多次经过摄像头,但应该算作1次。
如何更新我的查询以计算每月的天数而不是相机拍摄的天数?
假设您的 DateTime
字段名为 datetime
,一种可以考虑的方法是 DateHistogram 聚合:
{
"size": 0,
"query": {
"bool": {
"must": [
{
"match": {
"PersonID": "111"
}
},
{
"range": {
"datetime": {
"gte": "2017-05-01",
"lt": "2017-06-01"
}
}
}
]
}
},
"aggregations": {
"my_day_histogram": {
"date_histogram": {
"field": "datetime",
"interval": "1d",
"min_doc_count": 1
}
}
}
}
- 注意,在
must
子句中,我在 datetime
字段中使用了 range 术语(不是必需的,但您可以认为 Month
字段是多余的) .此外,您可能需要将范围术语中的日期格式编辑为您的映射
- my_day_histogram:通过设置
"interval": "1d"
. 将数据划分到不同天的桶中
"min_doc_count": 1
删除包含零个文档的存储桶。
其他方法,删除第 5 个月的 range/match 并扩展一年中每一天的直方图。
这也可以像这样与月份直方图聚合:
"aggregations": {
"my_month_histogram": {
"date_histogram": {
"field": "first_timestamp",
"interval": "1M",
"min_doc_count": 1
},
"aggregations": {
"my_day_histogram": {
"date_histogram": {
"field": "first_timestamp",
"interval": "1d"
}
}
}
}
}
我很清楚,在这两种方式中,您都需要计算表示天数的桶数。
我想得到一个人五月份在一个城镇停留的天数(Month
等于5)。
这是我的查询,但它为我提供了 myindex
中 PersonID
等于 111
且 Month
等于 5 的条目数。例如,此查询可能会给我类似 90 的输出,但每个月最多有 31 天。
GET myindex/_search?
{
"size":0,
"query": {
"bool": {
"must": [
{ "match": {
"PersonID": "111"
}},
{ "match": {
"Month": "5"
}}
]
} },
"aggs": {
"stay_days": {
"terms" : {
"field": "Month"
}
}
}
}
在 myindex
中,我有像 DateTime
这样的字段,其中包含某人通过相机注册的日期和时间,例如2017-05-01T00:30:08"
。所以,同一个人在一天中可能会多次经过摄像头,但应该算作1次。
如何更新我的查询以计算每月的天数而不是相机拍摄的天数?
假设您的 DateTime
字段名为 datetime
,一种可以考虑的方法是 DateHistogram 聚合:
{
"size": 0,
"query": {
"bool": {
"must": [
{
"match": {
"PersonID": "111"
}
},
{
"range": {
"datetime": {
"gte": "2017-05-01",
"lt": "2017-06-01"
}
}
}
]
}
},
"aggregations": {
"my_day_histogram": {
"date_histogram": {
"field": "datetime",
"interval": "1d",
"min_doc_count": 1
}
}
}
}
- 注意,在
must
子句中,我在datetime
字段中使用了 range 术语(不是必需的,但您可以认为Month
字段是多余的) .此外,您可能需要将范围术语中的日期格式编辑为您的映射 - my_day_histogram:通过设置
"interval": "1d"
. 将数据划分到不同天的桶中
"min_doc_count": 1
删除包含零个文档的存储桶。
其他方法,删除第 5 个月的 range/match 并扩展一年中每一天的直方图。 这也可以像这样与月份直方图聚合:
"aggregations": {
"my_month_histogram": {
"date_histogram": {
"field": "first_timestamp",
"interval": "1M",
"min_doc_count": 1
},
"aggregations": {
"my_day_histogram": {
"date_histogram": {
"field": "first_timestamp",
"interval": "1d"
}
}
}
}
}
我很清楚,在这两种方式中,您都需要计算表示天数的桶数。