AI Hints
Home›Elasticsearch Tutorial›Excluding and Context
Elasticsearch · Lesson 38 of 120

Query vs Filter Context

Does it score?.

⏱ 2 min read▶ Video at 34:48🎓 Free
Watch this lesson in the Elasticsearch courseWatch on YouTube ↗Full Elasticsearch course

Every query runs in one of two contexts. In query context, it asks, how well does this document match? In filter context, it only asks, does it match, yes or no?

  • How well?
  • Yes or no?
  • Two contexts

Two contexts

Query context calculates a relevance score, and that takes work. It's used by must and should. Filter context just says yes or no, so it's fast, and can be cached. It's used by filter and must not.

Query context

  • How well does it match?Calculates _scoremust, should

Filter context

  • Does it match?No score, cacheablefilter, must_not

Scores of zero

A bool with only a filter has no query context, so every score is zero. Run it. All the hits score zero point zero. If you want scores of one instead, use constant score.

Dev Tools Consoletext
GET products/_search?filter_path=hits.hits._score,hits.hits._source.name
{
  "query": {
    "bool": { "filter": { "term": { "category.keyword": "Lighting" } } }
  },
  "size": 3
}
Output
{
  "hits": {
    "hits": [
      {
        "_score": 0.0,
        "_source": {"name": "Bright 400 Headlamp"}
      },
      {"_score": 0.0, "_source": {"name": "Mini 200 Headlamp"}},
      {
        "_score": 0.0,
        "_source": {"name": "Rechargeable 600 Headlamp"}
      }
    ]
  }
}
Also uses _load
products

Summary

Query context scores documents, and filter context just decides yes or no, faster and cacheable. Next, practise with a real shop query.

Key takeaways
  • Query context
  • Filter context
  • Pick the right one
Next up: Practice: A Real Shop Query — put it all together