title: How to aggregate the result of aggregation in Elasticsearch?
body: <p>I want to aggregate the result of other aggregation using Elasticsearch. I have created the first aggregation I need:</p>
  
  <pre><code>es.search(index='stackoverflow', body = {
      "size":0,
      "query": {
          "bool": {
            "filter": {
                "match" : {"type": "Posts"}
            },
            "filter": {
                "match" : {"PostTypeId": "1"}
            }
          }
      },
      "aggs" : {
          "by_user": {
            "terms": {
              "field": "OwnerUserId"
            }
          }
      }
  })
  </code></pre>
  
  <p>This query takes all the documents of type <em>post</em> that are questions (<em>PostTypeId = 1</em>). Then, it aggregates by <em>OwnerUserId</em>, which counts the number of question posts of each user, giving the following result:</p>
  
  <pre><code>{'took': 0,
   'timed_out': False,
   '_shards': {'total': 1, 'successful': 1, 'skipped': 0, 'failed': 0},
   'hits': {'total': {'value': 10000, 'relation': 'gte'},
    'max_score': None,
    'hits': []},
   'aggregations': {'by_user': {'doc_count_error_upper_bound': 0,
     'sum_other_doc_count': 31053,
     'buckets': [{'key': '2230', 'doc_count': 223},
      {'key': '', 'doc_count': 177},
      {'key': '38304', 'doc_count': 158},
      {'key': '5997', 'doc_count': 144},
      {'key': '4048', 'doc_count': 130},
      {'key': '25813', 'doc_count': 119},
      {'key': '27826', 'doc_count': 119},
      {'key': '2633', 'doc_count': 115},
      {'key': '19919', 'doc_count': 114},
      {'key': '13938', 'doc_count': 111}]}}}
  </code></pre>
  
  <p>Now I want to do another aggregation over the results of the previous one: aggregate by <em>doc_count</em>, I mean grouping and counting the equal number of question posts. For the previous result, my desired result would be:</p>
  
  <pre><code>{'buckets': [{'key': '223', 'doc_count': 1},
      {'key': '177', 'doc_count': 1},
      {'key': '158', 'doc_count': 1},
      {'key': '144', 'doc_count': 1},
      {'key': '130', 'doc_count': 1},
      {'key': '119', 'doc_count': 2},
      {'key': '115', 'doc_count': 1},
      {'key': '114', 'doc_count': 1},
      {'key': '111', 'doc_count': 1}]}
  </code></pre>