title: ElasticSearch aggregation - filter and group by
body: <p>I'm new to elasticsearch, and trying to execute a query which do something similar to filter and group by.</p>
  
  <p>I was able to filter (by using filter) and executing a group by query by using 'terms', but couldn't build a query that does both.</p>
  
  <p>That's my query without grouping</p>
  
  <pre><code>{
    "size": 0,
    "aggs": {
      "group_by_city": {
          "filter": {
              "bool": {
                "must": [
                  {
                    "term": {
                      "account": "a"
                    }
                  },
                  {
                    "term": {
                      "appName": "b"
                    }
                  },
                  {
                    "range": {
                      "timestamp": {
                        "from": 1464713893304,
                        "to": 1465022700000
                      }
                    }
                  }
                ]
              }
            },
        "aggs": {
          "average_timing": {
            "avg": {
              "field": "t.timing1"
            }
          }
        }
      }
    }
  }
  </code></pre>
  
  <p>For grouping I've used:</p>
  
  <pre><code>{
    "size": 0,
    "aggs": {
      "group_by_country": {
        "terms": {
          "field": "country"
        },
        "aggs": {
          "average_balance": {
            "avg": {
              "field": "t.timing1"
            }
          }
        }
      }
    }
  }
  </code></pre>
  
  <p>Any ideas how can I combine the two?</p>