且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

弹性搜索过滤部分日期

更新时间:2023-02-08 20:28:50

根据您的问题,我假设您要查询, ñ一个过滤器(它们不同),您可以使用与范围查询相结合的日期数学/格式。



请参阅:范围查询用于



为了解释日期数学,请参阅以下链接



curl -XPOST http:// localhost:9200 / twitter / tweet / _search -d

  {
查询:{
range:{
birthday:{
gte:2014-01-01,
lte:2014-01-01
}
}
}
}

我用最新的弹性搜索测试了这个。 p>

QUESTION Maybe anyone has solution how to filter/query ElasticSearch data by month or day ? Let's say I need to get all users who celebrating birthdays today.

mapping


mappings:
    dob: { type: date, format: "dd-MM-yyyy HH:mm:ss||yyyy-MM-dd'T'HH:mm:ss'Z'||yyyy-MM-dd'T'HH:mm:ss+SSSS"}

and stored in this way:

 dob: 1950-06-03T00:00:00Z 

main problem is how to search users by month and day only. Ignore the year, because birthday is annually as we know.


SOLUTION I found solution to query birthdays with wildcards. As we know if we want use wildcards, the mapping of field must be a string, so I used multi field mapping.


mappings:
    dob:
        type: multi_field
        fields:
            dob: { type: date, format: "yyyy-MM-dd'T'HH:mm:ss'Z'}
            string: { type: string, index: not_analyzed }

and query to get users by only month and day is:

{
    "query": {
        "wildcard": {
            "dob.string": "*-06-03*"
        }
    }
}

NOTE This query can be slow, as it needs to iterate over many terms.

CONCLUSION It's not pretty nice way, but it's the only one I've found and it works!.

Based on your question I am assuming that you want a query, and not a filter (they are different), you can use the date math/format combined with a range query.

See: range query for usage

For explanation of date math see the following link

curl -XPOST http://localhost:9200/twitter/tweet/_search -d

{
  "query": {
    "range": {
        "birthday": {
            "gte" : "2014-01-01",
            "lte" : "2014-01-01"
        }
    }
  }
}

I have tested this with the latest elastic search.