I was speaking with a colleague recently and I mentioned I use a term
query over a date
field to find matches on a certain day, like this:
{
"query": {
"term": {
"@timestamp": {
"value": "2021-10-08"
}
}
}
}
That query returns all documents with an @timestamp
on 8th October 2021.
They were surprised by this, so we looked at the docs but couldn't find any reference to this behaviour. I had a suspicion that Elasticsearch was rewriting this query as a range
, which was confirmed after finding this line of code in the Elasticsearch source. The query effectively becomes this:
{
"query": {
"range": {
"@timestamp": {
"gte": "2021-10-08",
"lte": "2021-10-08"
}
}
}
}
The gte
rounds down, the lte
rounds up, so the range is for the full day.
Missing day components are replaced with 01
, so omitting that finds all documents on the first of the month, like this query:
{
"query": {
"term": {
"@timestamp": {
"value": "2021-10"
}
}
}
}
Is this feature of the term
query well-known? I can't remember how I stumbled on this behaviour but have been using it for a while. There's no reference to it in the docs for the term query or date field type.
George.