ElasticSearch: How to query a date field using a month & date range filter

不打扰是莪最后的温柔 提交于 2020-01-02 07:33:33

问题


Currently, I already know how to filter a date range from a (timestamp) date field. That's an easy one:

"range": {
    "date": {
        "gte": "2015-11-01",
        "lte": "2015-11-30"
    }
}

But how to filter dates when you are interested in ranges based on month like gte:"02-22" and lte:"03-21"? Is this possible?

Mapping:

PUT dob
{
    "mappings": {
        "test":{
            "properties": {
                "dob":{
                    "type": "date",
                    "format": "dateOptionalTime"
                }
            }
        }
    }     
}

Query:

GET /dob/test/_search
{
    "query": {
        "filtered": {
            "filter": {
                "bool": {
                    "must": [
                        {
                            "range": {
                                "date": {
                                    "gte": "02-11",
                                    "lte": "03-20"
                                }
                            }
                        },
                        {
                            "script": {
                                "script": "doc.dob.date.getDayOfMonth() >= min && doc.dob.date.getMonthOfYear() <= max",
                                "params": {
                                    "min": 12,
                                    "max": 2
                                }
                            }
                        }
                    ]
                }
            }
        }
    }
}

I want to output something like date greater than:02-11 & less than:03-20 but I don't want to change my date type format (yyyy-mm-dd) and also I don't want to search it by string. If i am doing something wrong please make me correct.


回答1:


You can specify format in date filter like

"date":
{
    "gte":"02-22","lte":03-20","format":"mm-dd"
}


来源:https://stackoverflow.com/questions/35626212/elasticsearch-how-to-query-a-date-field-using-a-month-date-range-filter

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