0

I'm testing with ElasticSearch and I'm having problems with ranged queries. Consider the following document that I've inserted:

curl -XPUT 'localhost:9200/test/test/test?pretty' -d '
{
  "name": "John Doe",
  "duration" : "10",
  "state" : "unknown"
}'

And now I'me trying to do a ranged query that catches all documents whose duration is between 5 and 15:

curl -XPOST 'localhost:9200/test/_search?pretty' -d '
{
  "query": {
    "range": {
      "duration": {
        "gte": "5",
        "lte": "15"
      }
    }
  }
}'

This returns no hits however if I run the Query like this:

curl -XPOST 'localhost:9200/test/_search?pretty' -d '
{
  "query": {
    "range": {
      "duration": {
        "gte": "10"
      }
    }
  }
}'

It returns the Document I've inserted earlier. How can I query ElasticSearch for documents with the duration value between 5 and 15.

1 Answer 1

1

The problem is that you are indexing your values as strings. This causes the range query not to work. Try indexing and querying as follows:

curl -XPUT 'localhost:9200/test/test/test?pretty' -d '
{
  "name": "John Doe",
  "duration" : 10,
  "state" : "unknown"
}'

curl -XPOST 'localhost:9200/test/_search?pretty' -d '
{
  "query": {
    "range": {
      "duration": {
        "gte": 5,
        "lte": 15
      }
    }
  }
}'

This wil yield the following result:

{
  "took" : 2,
  "timed_out" : false,
  "_shards" : {
    "total" : 5,
    "successful" : 5,
    "failed" : 0
  },
  "hits" : {
    "total" : 1,
    "max_score" : 1.0,
    "hits" : [ {
      "_index" : "test",
      "_type" : "test",
      "_id" : "test",
      "_score" : 1.0,
      "_source":
{
  "name": "John Doe",
  "duration" : 10,
  "state" : "unknown"
}
    } ]
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, truth is, i had already tried that multiple times but I've never tried to delete the document and insert it again, i kept updating the same object changing the duration field to integer and it never worked, however, deleting my old document and indexing it again made the ranged query work as intended.
Glad it works! The reason you have to delete your document is because if no mapping is specified, elastic will create a mapping automatically for your documents when you index for the first time. It then guesses the types to use for the document fields. In this case it decided to use a string to store the duration. Only when you delete your index, this automatically created mapping gets deleted as well.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.