title: Elasticsearch Group By Aggregation with Filtering Performance
body: <p>I am having a performance problem with Elasticsearch (6.3). There are 1B documents in my index, and I need to do an aggregation against a small subset of the data. </p>
  
  <p>My index looks like </p>
  
  <pre><code>    "s-data": {
          "mappings": {
              "s-type": {
                  "properties": {
                      "c": {
                          "type": "integer"
                      },
                      "r": {
                          "type": "keyword"
                      },
                      "s": {
                          "type": "integer"
                      },
                      "t": {
                          "type": "keyword"
                      }
                  }
              }
          }
      }
  }
  </code></pre>
  
  <p>and my query looks like</p>
  
  <pre><code>{
      "query":{
          "bool":{
              "filter":[
                  {"term":{"t": "foo"}},
                  {"term":{"c": 1}},
                  {"terms":{"r": ["foobar", "foobaz"]}},
                  {"term":{"s": 3}}
              ]
          }
      },
      "aggs":{
          "recips":{
            "terms": {"field": "r"}
          }
      }
  }
  </code></pre>
  
  <p>The query itself runs in 15ms, but once I tack on the aggregation the whole thing just times out. I assume that the aggregation is running against the entire 1B doc dataset. How can I make the aggregation run only against the results of my query?</p>