Ryan Papke
Ryan Papke

Reputation: 165

Casting when querying ElasticSearch data

Is there a way in elasticsearch where I can cast a string to a long value at query time?

I have something like this in my document: "attributes": [ { "key": "age", "value": "23" }, { "key": "name", "value": "John" }, ],

I would like to write a query to get all the persons that have an age > 23. For that I need to cast the value to an int such that I can compare it when the key is age.

The above document is an example very specific to this problem.

I would greatly appreciate your help.

Thanks!

Upvotes: 0

Views: 2128

Answers (1)

Nikolay Papakha
Nikolay Papakha

Reputation: 185

You can use scripting for that

POST /index/type/_search
{
  "query": {
     "filtered": {
       "filter": {
         "script": {
           "script": "foreach(attr :  _source['attributes']) {if ( attr['key']=='age') { return attr['value'] > ageValue;} } return false;",
           "params" : {
                "ageValue"  : 23
            }

         }
       },
       "query": {
         "match_all": {}
       }
     }
  }
}

UPD: Note that dynamic scripting should be enabled in elasticsearch.yml.

Also, I suppose you can archive better query performance by refactoring you document structure and applying appropriate mapping for age field.

Upvotes: 2

Related Questions