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

**URL:** <https://discuss.elastic.co/t/its-not-clear-that-its-not-possible-to-access-the-ctx-source-inside-a-function-in-a-painless-script/322013>\
**Category:** Elasticsearch\
**Tags:** painless\
**Created:** [December 26, 2022, 9:24pm UTC](https://discuss.elastic.co/t/its-not-clear-that-its-not-possible-to-access-the-ctx-source-inside-a-function-in-a-painless-script/322013 "2022-12-26T21:24:50Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![RafaelAdao](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/rafaeladao/32/115248_2.png) [@RafaelAdao](https://discuss.elastic.co/u/RafaelAdao)\
**Post date:** [December 26, 2022, 9:24pm UTC](https://discuss.elastic.co/t/its-not-clear-that-its-not-possible-to-access-the-ctx-source-inside-a-function-in-a-painless-script/322013/1 "2022-12-26T21:24:50Z")

</div>

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.

```auto
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.

```auto
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:

```auto
PUT my-index-000001/_doc/1
{
  "counter" : 1
}

```

- with error

```auto
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

```auto
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
    }
  }
}

```

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [January 23, 2023, 9:25pm UTC](https://discuss.elastic.co/t/its-not-clear-that-its-not-possible-to-access-the-ctx-source-inside-a-function-in-a-painless-script/322013/2 "2023-01-23T21:25:43Z")

</div>

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