ElasticSearch:如何使用小时范围过滤器查询日期字段 [英] ElasticSearch: How to query a date field using an hours-range filter

查看:337
本文介绍了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.

这篇关于ElasticSearch:如何使用小时范围过滤器查询日期字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆