简体   繁体   中英

Ranged Query with ElasticSearch

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM