Home > other >  elasticsearch range query not working just gives empty response
elasticsearch range query not working just gives empty response

Time:07-16

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"
      }
    }
  }
}

CodePudding user response:

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

CodePudding user response:

One quick check is the type of "Date" in the ES index mapping a datetime type with a specific format. If so the following query may be worth a try

try the boolean query

www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-bool-query.html

GET favorite/_search
{
  "query": {
    "bool": {
      "must":[ 
              {
                "range": {
                  "Date": {
                    "gte": "07/12/2022 16:04:30.496",
                    "lte": "07/12/2022 17:05:30.496"
                  }
                }
              }
      ]
    }
  }
}
  • Related