Filtered Query

edit

Deprecated in 2.0.0-beta1.

Use the bool query instead with a must clause for the query and a filter clause for the filter

The filtered query is used to combine a query which will be used for scoring with another query which will only be used for filtering the result set.

Exclude as many document as you can with a filter, then query just the documents that remain.

{
  "filtered": {
    "query": {
      "match": { "tweet": "full text search" }
    },
    "filter": {
      "range": { "created": { "gte": "now-1d/d" }}
    }
  }
}

The filtered query can be used wherever a query is expected, for instance, to use the above example in search request:

curl -XGET localhost:9200/_search -d '
{
  "query": {
    "filtered": { 
      "query": {
        "match": { "tweet": "full text search" }
      },
      "filter": {
        "range": { "created": { "gte": "now-1d/d" }}
      }
    }
  }
}
'

The filtered query is passed as the value of the query parameter in the search request.

Filtering without a query

edit

If a query is not specified, it defaults to the match_all query. This means that the filtered query can be used to wrap just a filter, so that it can be used wherever a query is expected.

curl -XGET localhost:9200/_search -d '
{
  "query": {
    "filtered": { 
      "filter": {
        "range": { "created": { "gte": "now-1d/d" }}
      }
    }
  }
}
'

No query has been specified, so this request applies just the filter, returning all documents created since yesterday.

Multiple filters

edit

Multiple filters can be applied by wrapping them in a bool query, for example:

{
  "filtered": {
    "query": { "match": { "tweet": "full text search" }},
    "filter": {
      "bool": {
        "must": { "range": { "created": { "gte": "now-1d/d" }}},
        "should": [
          { "term": { "featured": true }},
          { "term": { "starred":  true }}
        ],
        "must_not": { "term": { "deleted": false }}
      }
    }
  }
}