# Elastic painless script: Iteration on all documents

**URL:** <https://discuss.elastic.co/t/elastic-painless-script-iteration-on-all-documents/230686>\
**Category:** Elasticsearch\
**Tags:** painless\
**Created:** [May 1, 2020, 9:37am UTC](https://discuss.elastic.co/t/elastic-painless-script-iteration-on-all-documents/230686 "2020-05-01T09:37:44Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![jsonpaul](https://avatars.discourse-cdn.com/v4/letter/j/b19c9b/32.png) [@jsonpaul](https://discuss.elastic.co/u/jsonpaul)\
**Post date:** [May 1, 2020, 9:37am UTC](https://discuss.elastic.co/t/elastic-painless-script-iteration-on-all-documents/230686/1 "2020-05-01T09:37:44Z")

</div>

Hello everyone,

In elastic script params[\_source] or doc contexts returns only a single document and it allows us to iterate on fields but I need to get variables from all other documents to do my calculation. How can I do that?

I would be happy if anyone can explain on this example;  
Thanks a lot !

```auto
GET hockey/_search
{
  "query": {
    "function_score": {
      "script_score": {
        "script": {
          "lang": "painless",
          "source": """
            int total = 0;
            for (int i = 0; i < doc['goals'].length; ++i) {
              total += doc['goals'][i];
            }
            return total;
          """
        }
      }
    }
  }
}

```

---

<div class="post-metadata">

**Author:** ![Christian\_Dahlqvist](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/christian_dahlqvist/32/4617_2.png) [@Christian\_Dahlqvist](https://discuss.elastic.co/u/Christian_Dahlqvist)\
**Post date:** [May 2, 2020, 1:59pm UTC](https://discuss.elastic.co/t/elastic-painless-script-iteration-on-all-documents/230686/2 "2020-05-02T13:59:49Z")

</div>

Painless runs in the context of a single document, so you do not have access to other documents.

---

<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:** [May 30, 2020, 1:59pm UTC](https://discuss.elastic.co/t/elastic-painless-script-iteration-on-all-documents/230686/3 "2020-05-30T13:59:50Z")

</div>

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