# Access aggregation key inside script

**URL:** <https://discuss.elastic.co/t/access-aggregation-key-inside-script/91266>\
**Category:** Elasticsearch\
**Created:** [June 29, 2017, 10:29am UTC](https://discuss.elastic.co/t/access-aggregation-key-inside-script/91266 "2017-06-29T10:29:21Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![Wullschi](https://avatars.discourse-cdn.com/v4/letter/w/9dc877/32.png) [@Wullschi](https://discuss.elastic.co/u/Wullschi)\
**Post date:** [June 29, 2017, 10:29am UTC](https://discuss.elastic.co/t/access-aggregation-key-inside-script/91266/1 "2017-06-29T10:29:21Z")

</div>

Hi, I have a filter script inside an Aggregation. Inside this script i would like to access the key from the outer Aggregation. Is this possible?

```
"aggs": {
        "category": {
          "terms": {
            "field": "category",
            "size": 20
          },
          "aggs": {
            "my_filter": {
              "filter": {
                "script": {
                  "lang": "painless",
                  "inline": "if(category_key == 'phone'){do something}else{do something else}"
                }
              }
            }
          }
        }
      }

```

Thanks!

---

<div class="post-metadata">

**Author:** ![colings86](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/colings86/32/44960_2.png) [@colings86](https://discuss.elastic.co/u/colings86)\
**Post date:** [June 29, 2017, 10:43am UTC](https://discuss.elastic.co/t/access-aggregation-key-inside-script/91266/2 "2017-06-29T10:43:04Z")

</div>

It's not possible for aggregations to access the key for the bucket they are in. To achieve what you want you could split your terms aggregation into two separate aggregations; a filter aggregation for `category:phone` which contains the filter you want to apply on the `phone` documents, and also a terms aggregation similar to your current one but with `"excludes": "phone"` so the phone documents do not appear in this aggregation since you already have that in the separate filter aggregation.

Hope that helps.

---

<div class="post-metadata">

**Author:** ![Wullschi](https://avatars.discourse-cdn.com/v4/letter/w/9dc877/32.png) [@Wullschi](https://discuss.elastic.co/u/Wullschi)\
**Post date:** [June 29, 2017, 10:53am UTC](https://discuss.elastic.co/t/access-aggregation-key-inside-script/91266/3 "2017-06-29T10:53:40Z")

</div>

Thanks you!

---

<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:** [July 27, 2017, 10:53am UTC](https://discuss.elastic.co/t/access-aggregation-key-inside-script/91266/4 "2017-07-27T10:53:52Z")

</div>

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