Home > Back-end >  Elasticsearch - how to check for key exist script query parameters?
Elasticsearch - how to check for key exist script query parameters?

Time:12-02

Is there any way to return null if there is no corresponding value?

example) Since params do not have a field4 value, I want the null value to be returned to the syn variable.

"aggs": {
    "countries": {
      "terms": {
        "script": {
          "params": {
            "field1": "country",
            "field2": "test",
            "field3": "test"
          },
          "inline": "def syn = field4; if (syn == null) doc[country].value;"
        }
      }
    }
  }

Currently, errors always occur if there is no corresponding value.

"caused_by": {
   "type": "missing_property_exception",
   "reason": "No such property: field1 for class: e5ce2464b456f9c0fa360269abc927e65998ecf7"
}

I am using groovy and elasticsearch version 2.2

I can't use Python or JavaScript, which requires additional plug-ins to be installed.

How can I get a null value without causing an error if there is no value?

Thanks

CodePudding user response:

You have a boolean value called empty that indicates you whether the document has such a field or not.

So you should do it this way

      "inline": "def syn = field4 ?: 'dummy'; return (doc[syn].empty) ? null : doc[syn].value;"

UPDATE: To detect a missing parameter variable in Groovy is trivial if we know the script class name. But since the script class is created dynamically (e.g. e5ce2464b456f9c0fa360269abc927e65998ecf7), it makes the process not trivial at all. One way to circumvent this is to add a try/catch block around your code, so that the code can fail but at least we can catch it, basically like this:

      "inline": "try { def syn = field4; return (doc[syn].empty) ? null : doc[syn].value; } catch (e) { return null } "

However, ES introduced some security hardening and class whitelisting for scripting in 2.2. One way to achieve this is to whitelist a few Exception classes in your .java.policy file, like this:

grant {
  permission org.elasticsearch.script.ClassPermission "java.lang.Throwable";
  permission org.elasticsearch.script.ClassPermission "java.lang.Exception";
  permission org.elasticsearch.script.ClassPermission "groovy.lang.GroovyException";
};
  • Related