title: Multiple filters and an aggregate in elasticsearch
body: <p>How can I use a filter in connection with an aggregate in elasticsearch?</p>
  
  <p>The official documentation gives only trivial examples for <a href="http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-and-filter.html">filter</a> and for <a href="http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-aggregations-bucket-histogram-aggregation.html">aggregations</a> and no formal description of the query dsl - compare it e.g. with <a href="http://www.postgresql.org/docs/9.3/static/sql-select.html">postgres documentation</a>.</p>
  
  <p>Through trying out I found following query, which is accepted by elasticsearch (no parsing errors), but ignores the given filters:</p>
  
  <pre><code>{
    "filter": {
      "and": [
        {
          "term": {
            "_type": "logs"
          }
        },
        {
          "term": {
            "dc": "eu-west-12"
          }
        },
        {
          "term": {
            "status": "204"
          }
        },
        {
          "range": {
            "@timestamp": {
              "from": 1398169707,
              "to": 1400761707
            }
          }
        }
      ]
    },
    "size": 0,
    "aggs": {
      "time_histo": {
        "date_histogram": {
          "field": "@timestamp",
          "interval": "1h"
        },
        "aggs": {
          "name": {
            "percentiles": {
              "field": "upstream_response_time",
              "percents": [
                98.0
              ]
            }
          }
        }
      }
    }
  }
  </code></pre>
  
  <p>Some people suggest using <code>query</code> instead of <code>filter</code>. But the official documentation generally recommends <a href="http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-filters.html">the opposite</a> for filtering on exact values. Another issue with <code>query</code>: while filters offer an <a href="http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-and-filter.html"><code>and</code></a>, <code>query</code> does not.</p>
  
  <p>Can somebody point me to documentation, a blog or a book, which describe writing non-trivial queries: at least an aggregate plus multiple filters.</p>