Reputation: 23187
I'd like to get whichever document has a date field dateField
where year(dateField) = 2016
.
In short, I need to get all the documents which has informed dateField
on 2016.
Upvotes: 0
Views: 125
Reputation: 217274
If you only want to check for a single year, the easiest way is to use a range
filter in which you check that the dateField
is between Jan 1st and Dec 31st of year 2016:
POST index/_search
{
"query": {
"bool": {
"filter": [
{
"range": {
"dateField": {
"gte": "2016-01-01T00:00:00.000Z",
"lt": "2017-01-01T00:00:00.000Z"
}
}
}
]
}
}
}
You have two other solutions:
year
field inside your document at indexing time so you can search on it using a term
or range
query/filterscript
filter at search timeThe first option is more performant, but in case you want to try the second options, it goes like this:
POST index/_search
{
"query": {
"bool": {
"filter": [
{
"script": {
"script": {
"inline": "doc.dateField.date.getYear() == year",
"params": {
"year": 2016
}
}
}
}
]
}
}
}
Upvotes: 3