Ranjit Iyer
Ranjit Iyer

Reputation: 887

Different between query and filters in ElasticSearch

I am a little bit confused about the differences between queries and filters. My confusion stems from the following sentences that I read in the documentation.

  1. Filters are recommended over queries because filters do not trigger score computation.
  2. Filters should be used only when the response is a yes/no or an exact search.
  3. Filters can have queries called 'query filters' (like 'term filter', etc.)

All I want to is filter by 4 attribute values, put in a date range and sum (aggregate) over a few fields. Like so

sum (salary, tenure) where name = A AND age = B AND join_date between X and Y 

Upvotes: 3

Views: 4865

Answers (1)

AaronM
AaronM

Reputation: 2459

Think of a query as a fuzzy match, and a filter as a traditional database style query. If it helps think of query as a database LIKE, though nicer.

The query is going to analyze your search break it down into bits and then search for documents that were similar to your query. Each document gets a score the best score wins and is returned in score order in the result set. All of this scoring is expensive and will slow your response.

A filter says simply do I include or exclude this piece of data, no score involved. Either the filter matches and the doc is included or it does not and it is excluded. This all happens very quickly and there is no sorting involved.

Your sample "query" does not require a query, it is a filter on name = A and age = B. A query might include documents that match name = AA because it is kinda like A. So you have a term filter on name and a term filter on age with a range filter on join_date. Then you can do your aggregation to get your SUM.

{
"query": {
    "filtered": {
        "filter": {
            "and": [
                { "range": {
                    "join_date": {
                        "from": "X",
                        "to": "Y"
                    }
                }},
                {"term": { "name": "A" }},
                {"term": { "age": "B" }},
            ]
        }
    }
},
"size": 0,
"aggs" : {
    "salary_sum": {
            "sum": { "field": "salary" }
    },
    "tenure_sum": {
            "sum": { "field": "tenure" }
    }
}
}

Upvotes: 12

Related Questions