elasticsearch range query not working just gives empty response

Viewed 58

In kibana I added this info to my index.

PUT favorite/_doc/1
{
  "first_name": "Lisa",
  "Date": "07/12/2022 16:04:30.496"
}

PUT favorite/_doc/2
{
  "first_name": "Ann",
  "Date": "07/12/2022 17:04:30.496"
}

PUT favorite/_doc/3
{
  "first_name": "Ming",
  "Date": "07/12/2022 18:04:30.496"
}

But when I run this query down below I get no results back. I'm not sure why this is happening and how can I fix this

GET favorite/_search
{
  "query": {
    "range": {
      "Date": {
        "gte": "07/12/2022 16:04:30.496",
        "lte": "07/12/2022 17:05:30.496"
      }
    }
  }
}
2 Answers

Issue is that you created index without defining the explicit mapping for Elasticsearch index and your date field is not in the format Elasticsearch supports to detect automatically, and that way your date field is indexed as text and keyword as shown below

 "mappings": {
            "properties": {
                "Date": {
                    "type": "text",
                    "fields": {
                        "keyword": {
                            "type": "keyword",
                            "ignore_above": 256
                        }
                    }

                }

And range query is not supported on the text fields, hence you are not getting result for your query.

Solution

Although Elasticsearch detects data field automatically but it needs to be in below formats as explained in the official doc

[ "strict_date_optional_time","yyyy/MM/dd HH:mm:ss Z||yyyy/MM/dd Z"]

So, either you change your date format if you are not defining the explicit mapping for your index, or define explicit mapping with date field in the format you want to fix issue

Related