# Trouble nesting two bucket aggregations

**URL:** <https://discuss.elastic.co/t/trouble-nesting-two-bucket-aggregations/49148>\
**Category:** Elasticsearch\
**Created:** [May 4, 2016, 10:14am UTC](https://discuss.elastic.co/t/trouble-nesting-two-bucket-aggregations/49148 "2016-05-04T10:14:59Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![dandrestor](https://avatars.discourse-cdn.com/v4/letter/d/7cd45c/32.png) [@dandrestor](https://discuss.elastic.co/u/dandrestor)\
**Post date:** [May 4, 2016, 10:14am UTC](https://discuss.elastic.co/t/trouble-nesting-two-bucket-aggregations/49148/1 "2016-05-04T10:14:59Z")

</div>

I am running the following query:

```
"aggs": {
    "chains": {
      "terms": {
        "field": "E2EID"
      },
      "aggs": {
        "chainresult": {
          "max": {
            "field": "error_code"
          }
        }
      }
    }
  }

```

And I am getting the following results:

```
"aggregations": {
    "chains": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": [
        {
          "key": "00000000-0000-0000-0000-1462354048000110",
          "doc_count": 13,
          "chainresult": {
            "value": 2
          }
        },
        {
          "key": "00000000-0000-0000-0000-1462354047850268",
          "doc_count": 4,
          "chainresult": {
            "value": 0
          }
        },
        {
          "key": "00000000-0000-0000-0000-1462354045636167",
          "doc_count": 3,
          "chainresult": {
            "value": 0
          }
        },
        {
          "key": "00000000-0000-0000-0000-1462354055161255",
          "doc_count": 2,
          "chainresult": {
            "value": 0
          }
        }
      ]
    }
  }

```

How can I nest another aggregation here, so I count how many buckets in the aggregation above there are, for each `chainresult.value`? Basically I would like to derive the following result:

`"buckets": [{ "key": "2", "value": "1" }, {"key": "0", "value": "3"}]`

Many thanks,  
Dan

---

<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 5, 2017, 10:54pm UTC](https://discuss.elastic.co/t/trouble-nesting-two-bucket-aggregations/49148/2 "2017-07-05T22:54:06Z")

</div>


