Bandicoot
Bandicoot

Reputation: 3949

Elasticsearch range filter on strings returning incorrect results

In my index, I have a field called "time" that is of type "string". There's another field "date" of type "date".

When I try to query the index and filter the results based on time, I am getting incorrect results. For example, my query is: {"and": { "filters": [ { "term": { "date": "2015-02-06" } }, { "range": { "time": { "from": "22:11", "to": "23:59", "include_lower": true, "include_upper": true } } }

And in the results I get fields for which the date is "2015-02-06", but the time is "16:01", "07:01" etc.

What am I doing wrong ?

Upvotes: 0

Views: 382

Answers (1)

Sloan Ahrens
Sloan Ahrens

Reputation: 8718

You need to format your time field as such, for your range filter to work. I don't think "range" knows what to do with a "string" field.

This worked for me: "time" : { "type": "date", "format": "HH:mm" }.

Here's the full example I used:

DELETE /test_index

PUT /test_index
{
   "settings": {
      "number_of_shards": 1
   },
   "mappings": {
      "doc": {
         "properties": {
             "time" : { "type": "date", "format": "HH:mm" },
             "date" : { "type": "date" }
         }
      }
   }
}

POST /test_index/_bulk
{"index":{"_index":"test_index","_type":"doc","_id":1}}
{"date": "2015-02-06","time": "16:01"}
{"index":{"_index":"test_index","_type":"doc","_id":2}}
{"date": "2015-02-06","time": "07:01"}
{"index":{"_index":"test_index","_type":"doc","_id":3}}
{"date": "2015-02-06","time": "22:30"}
{"index":{"_index":"test_index","_type":"doc","_id":4}}
{"date": "2015-02-08","time": "15:30"}

POST /test_index/_search
{
   "query": {
      "filtered": {
         "query": {
            "match_all": {}
         },
         "filter": {
            "and": {
               "filters": [
                  {
                     "term": {
                        "date": "2015-02-06"
                     }
                  },
                  {
                     "range": {
                        "time": {
                           "from": "22:11",
                           "to": "23:59",
                           "include_lower": true,
                           "include_upper": true
                        }
                     }
                  }
               ]
            }
         }
      }
   }
}
...
{
   "took": 5,
   "timed_out": false,
   "_shards": {
      "total": 1,
      "successful": 1,
      "failed": 0
   },
   "hits": {
      "total": 1,
      "max_score": 1,
      "hits": [
         {
            "_index": "test_index",
            "_type": "doc",
            "_id": "3",
            "_score": 1,
            "_source": {
               "date": "2015-02-06",
               "time": "22:30"
            }
         }
      ]
   }
}

Upvotes: 1

Related Questions