0

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

1 Answer 1

2

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";
};
Sign up to request clarification or add additional context in comments.

7 Comments

Same Error Occured def syn = field4; There seems to be an error in that part before checking the importy.
Oh I see what you mean now. Let me update my answer
I've updated my answer, can you try again? Sorry I cannot test it, because I can't install 2.2 anymore, too old.
not work same error occured
Ok, I did some more research and updated my answer. Please give it a try
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.