how to check for key exist in elastic-search painless parameters?
Asked Answered
K

1

8

How to check for key exists in painless script map parameters. In below query check a.toString() key exist in params I've tried everything but didn't get it to work. Please help me

mapping :

"id": {
   "type": "long"
}

query:

{
  "query":{
    "bool":{
      "filter":[
        {
          "script": {
            "script": {
               "lang": "painless",
               "params": {
                 "29232":2541,
                 "minDistance": 0
               },
               "source": "def a=doc['id'].getValue();double distance=params[a.toString()]; return distance <= 1000 && distance >= params['minDistance']"
            }
          }
        }
      ]
    }
  }
}
Karyosome answered 1/7, 2019 at 10:26 Comment(0)
Z
9

The params is just a Java Map object. So, the following checks if the key exists in the params and exits early with a false if it does not exist.

GET test/_search
{
  "query":{
    "bool":{
      "filter":[
        {
          "script": {
            "script": {
               "lang": "painless",
               "params": {
                 "29232":2541,
                 "minDistance": 0
               },
               "source": """
               def a=doc['id'].getValue();
               if (!params.containsKey(a.toString())) {
                 return false;
               }
               double distance=params[a.toString()]; 
               return distance <= 1000 && distance >= params['minDistance']
               """
            }
          }
        }
      ]
    }
  }
}
Zarger answered 1/7, 2019 at 12:32 Comment(1)
Thanks , it really helped meKaryosome

© 2022 - 2025 — McMap. All rights reserved.