ElasticSearch:如何使用小时范围过滤器查询日期字段
目前,我已经知道如何从(时间戳)日期字段过滤日期范围。这很简单:
Currently, I already know how to filter a days range from a (timestamp) date field. That's an easy one:
"range": {
"date": {
"gte": "2015-11-01",
"lte": "2015-11-30"
}
}
但是,当您对基于gte:8:00:00和lte:10:00:00的小时感兴趣的范围时,如何过滤日期?这可能吗?
But how to filter dates when you are interested in ranges based on hours like gte:"8:00:00" and lte:"10:00:00"? Is this possible?
我的要求换句话说:
如何获取本月发生的所有事件(15-11-01 / 15-11-30),但只能在8:00:00 am和10:00:00?
My requirement in other words: How to get all the events happening this month (15-11-01/15-11-30) but only between 8:00:00 am and 10:00:00?
您可以使用范围
过滤器以过滤正确的日期,然后使用脚本
过滤器来过滤所需的时间,如下所示:
You can do it with your range
filter to filter the correct days and then with a script
filter to filter the desired hours, like this:
{
"query": {
"filtered": {
"filter": {
"bool": {
"must": [
{
"range": {
"date": {
"gte": "2015-11-01",
"lte": "2015-11-30"
}
}
},
{
"script": {
"script": "doc.date.date.getHourOfDay() >= min && doc.date.date.getHourOfDay() <= max",
"params": {
"min": 8,
"max": 10
}
}
}
]
}
}
}
}
}
请注意,您需要确保启用动态脚本,以使此查询正常工作。
Note that you need to make sure to enable dynamic scripting in order for this query to work.