title: How to filter the results from a composite aggregation?
body: <p>I want to filter the results of the composite aggregation which inside has a top_hits aggregation. So I first group my data with a top_hits, then I use this as a subaggregation inside my composite aggregation that has a single source based on an Id and I don't know how to filter those gruped results.</p>
  
  <p>I've tried using the filters aggregation but I'm not sure since composite aggregation must be the father of all aggregations. Tried different combinations of these aggregation but none of these show me the results as I want.</p>
  
  <pre><code>{
    "size": 0,
    "aggs": {
      "grouped_data": {
        "composite": {
          "sources": [
            {
              "artifact": {
                "terms": {
                  "field": "artifactId.keyword"
                }
              }
            }
          ],
          "size": 20
        },
        "aggs": {
          "top_artifacts_hits": {
            "top_hits": {
              "size": 1,
              "sort": [{
                "initialDate": {
                  "order": "desc"
                }
              }]
            }
          }
        }
      }
    }
  }
  </code></pre>
  
  <p>I tried using the <code>query</code> API for filtering but that is not a good option for me since the filters I want to apply are meant for the grouped results. Using some <code>query</code> before the main aggregation makes ElasticSearch query first and then group. I need it to be backwards. I'm using ES 6.3 under AWS.</p>
  
  <p>So my documents look something like this:</p>
  
  <pre><code>{
    "artifactId": "foo",
    "clientId": "bar",
    "artifactState": "foozz",
    "initialDate": 1559745246
  }
  </code></pre>
  
  <p>What I need to do is to get the last <code>artifactState</code> based on the <code>initialDate</code> for each different <code>artifactId</code> so this is why I'm using top_hits + composite.</p>