title: Elasticsearch: Using the results of a Metric Aggregation to filter the elements of a bucket and run additional aggregations
body: <p>Given a dataset like</p>
  
  <pre><code>[{
      "type": "A",
      "value": 32
  }, {
      "type": "A",
      "value": 34
  }, {
      "type": "B",
      "value": 35
  }]
  </code></pre>
  
  <p>I would like to perform the following aggregation:</p>
  
  <ul>
  <li>Firstly, I would like to group by "type" in buckets using the <em>terms</em>
  aggregation.</li>
  <li>After that, I would like to calculate some metrics of the field "value" using the <em>extended_stats</em>.</li>
  <li>Knowing the <em>std_deviation_bounds</em> (upper and lower) I would like to
  calculate the average value of the elements of the bucket excluding
  those outside the range [std_deviation_bounds.lower,
  std_deviation_bounds.upper]</li>
  </ul>
  
  <p>First and second point of my list are trivial. I would like to know if the third point, using information of a sibling metric aggregation result to filter out elements of the bucket and recalculate an average is possible. And, if it is, I would like to have a hint of the aggregation structure I would need to use.</p>
  
  <p>The version of the Elasticsearch instance is 5.0.0</p>