问题
I have a field with the following mapping:
birthdate: { type: :date, format: :dateOptionalTime }
- I need to find everyone who were born in month of May (including all years)
- Another query is to find all people who were born on 'August 25' (including all years)
What would be the query for that?
回答1:
You can achieve this with a script filter
All people born in May of any year:
{
"query": {
"filtered": {
"filter": {
"script": {
"script": "doc.birthdate.date.monthOfYear == 5"
}
}
}
}
}
All people born on August 25th (any year)
{
"query": {
"filtered": {
"filter": {
"script": {
"script": "doc.birthdate.date.monthOfYear == 8 && doc.birthdate.date.dayOfMonth == 25"
}
}
}
}
}
回答2:
GET index_name/doc_type/_search
{
"query": {
"bool" : {
"filter" : {
"script" : {
"script" : {
"source": "doc.field_name.date.getMonthOfYear() == month_number",
"lang": "painless"
}
}
}
}
}
}
回答3:
Just for the archives, ES 7 brought some braking changes https://www.elastic.co/guide/en/elasticsearch//reference/current/breaking-changes-7.0.html#_getdate_and_getdates_removed
It is now:
POST /people/_search?size=50
{
"query": {
"bool" : {
"filter" : {
"script" : {
"script" : {
"source": "doc['jour'].value.getMonthValue() == 5",
"lang": "painless"
}
}
}
}
}
}
回答4:
First question:
POST /test_index/_search
{
"query": {
"filtered": {
"filter": {
"range": {
"birthdate": {
"gte": "2015-05-01",
"lt": "2015-06-01"
}
}
}
}
}
}
Second question:
POST /test_index/_search
{
"query": {
"filtered": {
"filter": {
"range": {
"birthdate": {
"gte": "2015-08-25",
"lte": "2015-08-25"
}
}
}
}
}
}
Here's the code I used to test it:
http://sense.qbox.io/gist/36c800cabbe4143ecf72144d02e58e267c1e761a
来源:https://stackoverflow.com/questions/32640437/elasticsearch-date-query-people-who-were-born-in-a-certain-month