It's not clear that it's not possible to access the `ctx['_source']` inside a function in a painless script

It's not clear to me that it's not possible to access the ctx['_source'] inside a function in a painless script. I looked in the documentation and couldn't find anything about it.

Below is an example of the code I was trying to run. The script was giving compilation error.

void initialize(def attrName, def defaultValue) {
  if (ctx._source[attrName] == null) {
    ctx._source[attrName] = defaultValue;
  }
}
initialize("events", []);
initialize("my_counter", 0);
...
...

I did a little refactoring to solve my problem. But I didn't find anything in the documentation about this limitation.

void initialize(def source, def attrName, def defaultValue) {
  if (source[attrName] == null) {
    source[attrName] = defaultValue;
  }
}
initialize(ctx._source, "events", []);
initialize(ctx._source, "my_counter", 0);
...
...

Here is a full example:

PUT my-index-000001/_doc/1
{
  "counter" : 1
}
  • with error
POST my-index-000001/_update/1
{
  "script": {
    "source": "void add(def value) { ctx._source.counter += value } add(params.count)",
    "lang": "painless",
    "params": {
      "count": 1
    }
  }
}
  • fixed
POST my-index-000001/_update/1
{
  "script": {
    "source": "void add(def source, def value) { source.counter += value } add(ctx._source, params.count);",
    "lang": "painless",
    "params": {
      "count": 1
    }
  }
}

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.