Querying and relevance
match, term, bool with must/should/filter, BM25, boosting, and reading the explain output.
A database query returns the rows that match. A search query returns the documents that match ranked by how well, and the ranking is the feature: the difference between "here are 4,000 results" and "the one you wanted is first". This lesson is the query DSL's two halves — the part that filters and the part that scores — the formula behind the score, the levers that change it, and how to read the engine's explanation when the wrong document wins.
Query context and filter context
Every clause in Elasticsearch runs in one of two contexts. In query context the clause answers "how well does this document match?" and contributes to the score. In filter context it answers "does this document match, yes or no?", contributes nothing to the score, and — the operational half — is cached as a bitset and reused across queries. Status codes, date ranges, tenant ids, categories: filters. The text the user typed: a query. Putting a status: PAID condition in query context wastes CPU scoring a term that is the same for every match; putting the user's words in filter context returns unranked results.
The bool query
{
"query": {
"bool": {
"must": [ { "match": { "title": { "query": "kafka consumer lag", "operator": "and" } } } ],
"should": [ { "match_phrase": { "title": "consumer lag" } },
{ "term": { "tags": "kafka" } } ],
"filter": [ { "term": { "status": "PUBLISHED" } },
{ "range": { "publishedAt": { "gte": "now-1y" } } } ],
"must_not": [ { "term": { "category": "internal" } } ]
}
}
}must clauses must match and score; should clauses are optional and add to the score when they match (with minimum_should_match making some of them required); filter and must_not are filter context. The leaf queries: match analyses the query text with the field's analyser and matches any of the terms (operator: and requires all); match_phrase requires them adjacent, in order; multi_match runs one query across several fields with a type that decides how their scores combine (best_fields for "the one field that matches best", cross_fields for a name split across first and last); term matches one exact term — on a keyword field, always, and on a text field only by accident, because the query is not analysed and PAID will never equal the indexed paid; range, exists, prefix, wildcard (slow), fuzzy for typos within an edit distance. Almost every real search is a bool with the user's text in must, the boosts in should, and everything structural in filter.
BM25: what the score is
The default scoring function is BM25, and its three inputs explain most surprising rankings:
- Term frequency: a document that mentions
kafkafive times scores higher than one that mentions it once — but with saturation, so the fiftieth mention adds almost nothing. That is thek1parameter, and it is why keyword-stuffed documents stopped winning. - Inverse document frequency: a term that appears in few documents is worth more than one that appears in most.
kafkain a Kafka blog is nearly worthless;outboxis rare and decisive. Stop words are the limit of this: they appear everywhere and are worth nothing, which is why removing them changes little. - Field length normalisation: a match in a 5-word title counts more than the same match in a 5,000-word body, because the short field is "about" the term more. The
bparameter controls how strongly.
Scores are per shard, computed from that shard's term statistics, so a small index with few documents per shard can rank inconsistently between shards; search_type=dfs_query_then_fetch gathers global statistics at a cost, and a single-shard index avoids the problem for anything under a few million documents. Scores are also not comparable across queries: 12.4 for one query and 3.1 for another means nothing about either.
Boosting: deciding what matters more
BM25 ranks by text alone. A product search wants in-stock items first, a knowledge base wants recent articles first, a marketplace wants the well-reviewed seller first — signals the text does not carry. The levers, cheapest first:
- Field boosts:
multi_matchwithfields: ["title^3", "body"]makes a title match worth three times a body match. shouldclauses: an optionaltermontagsormatch_phraseon the title adds score when it hits and costs nothing when it does not — the example above.booston a clause, for weighting one signal over another.function_score(or the newerrank_featureanddistance_featurequeries): multiply or add to the score from a field —field_value_factoronpopularity, agaussdecay onpublishedAtso recency fades smoothly, afilterwith aweightfor in-stock. This is where business rules meet relevance, and where a small change reorders every result.rescore: rerank only the top N with an expensive query, so the cheap query finds candidates and the expensive one orders them.
The discipline around all of it: keep a set of judged queries — fifty real queries with the result a product owner says should be first — and run them as a test against every relevance change. Relevance tuning without that is moving a slider and hoping; the testing course's contract-test idea applies to search results too.
Explain: why this document, and why not that one
GET /articles/_explain/42?q=... (or "explain": true on the search) returns the score's derivation for one document: each clause's contribution, and inside each, the term frequency, the IDF, the field length and the parameters that produced the number. Read it for two documents — the one that won and the one that should have — and the difference is usually one of: a term the losing document does not contain because analysis produced a different term (back to _analyze), a field-length penalty on a long document, an IDF that made a common word worthless, or a boost that fired for the wrong one. The _validate/query?explain=true endpoint shows how the query was rewritten before running, which is where a term query on a text field reveals itself.
The other diagnostic is the search profiler ("profile": true), which is EXPLAIN ANALYZE for search: time per query component per shard, and the wildcard or the unbounded range that is costing the milliseconds.
Under the hood: the BM25 formula, and what it fixed in plain TF-IDF
The "term frequency, rarity, field length" description above is the intuition; the actual function combines them in a specific way, and the shape of the combination — not just the three ideas — is what makes BM25 behave better than naive TF-IDF in practice. For one query term t against one document D, the widely used form (the one Lucene, and so Elasticsearch, computes per term before summing across the query's terms) is:
score(t, D) = IDF(t) · ( f(t,D) · (k1 + 1) ) / ( f(t,D) + k1 · (1 − b + b · |D| / avgdl) )Reading each piece against what it controls:
f(t,D)is the raw count oftinD— the term frequency the earlier section named.k1(Elasticsearch's default is1.2) sets how fast that count saturates. Look at the fraction asf(t,D)grows: the numerator grows linearly with it, but so does part of the denominator, so the ratio approaches a ceiling instead of climbing forever. A document mentioningkafkafifty times scores only slightly higher than one mentioning it twenty times — plaintf × idf, with no such term in the denominator, would keep rewarding repetition without limit, which is exactly the keyword-stuffing incentive BM25 removes.b(default0.75) sets how much document length relative to the average (|D| / avgdl) discounts that same term frequency.b = 1fully normalises by relative length;b = 0turns length normalisation off entirely, so a term appearing twice counts the same whether the document is 10 words or 10,000. The default sits close to full normalisation but not all the way, because some of a long document's extra length is legitimately more content, not padding.IDF(t)is not simplylog(N / n(t))(the classic TF-IDF form,Ndocuments total,n(t)containing the term). Lucene's BM25 uses a smoothed version close toln(1 + (N − n(t) + 0.5) / (n(t) + 0.5))— the exact smoothing constants have shifted slightly across Lucene versions and differ from the original Robertson–Spärck Jones probabilistic derivation, but the shape holds regardless of the exact constant: it keeps the weight defined and non-negative even for a term that appears in nearly every document, while still growing sharply for a term that appears in almost none.
What this fixes, concretely, versus plain TF-IDF: classic TF-IDF has no saturation term in its denominator, so term frequency contributes without bound, and no length normalisation is built in at all (any length adjustment has to be bolted on separately, and often was not). BM25 — developed through the Okapi information-retrieval experiments and TREC evaluations in the 1990s — folded both fixes into one formula with two tunable knobs (k1, b) instead of leaving them as ad-hoc adjustments, which is a large part of why it became the default scoring function for Lucene-based engines rather than one option among many.
Because saturation and length normalisation are separate knobs, they can be reasoned about separately: raising k1 makes repeated occurrences matter more before saturating; lowering b makes long documents stop being penalised for their length. Both are index-level (or per-field, via a custom similarity) settings, not something a query changes per request — which is why the "judged queries" discipline from the section above matters more than hand-tuning k1/b: a change to either affects every query against that field, and the only honest way to know whether it helped is the same regression test a code change would get.
Try it yourself
Work through why one document outranks another
Two documents both contain the term kafka. The corpus has N = 1,000 documents total, and kafka appears in n(t) = 100 of them (so it's a fairly common term in this corpus — a Kafka-focused blog, say). Document A is short (|A| = 50 words, and the average document length avgdl = 200 words) and mentions kafka twice. Document B is long (|B| = 800 words) and mentions kafka six times. Using k1 = 1.2, b = 0.75, which one gets more credit for the kafka term, and why?
Work it through in three pieces: IDF is shared, then compare the length-adjusted denominators
IDF(kafka) is the same number for both documents — it depends only on the corpus (N and n(t)), not on which document is being scored — so it does not decide the winner here; only the term-frequency fraction does. That fraction is f(t,D) · (k1+1) / (f(t,D) + k1 · (1 − b + b · |D|/avgdl)).
For document A: |A|/avgdl = 50/200 = 0.25, so the length factor is 1 − 0.75 + 0.75 × 0.25 = 0.4375. The denominator is 2 + 1.2 × 0.4375 ≈ 2.525, and the numerator is 2 × 2.2 = 4.4, giving roughly 4.4 / 2.525 ≈ 1.74.
For document B: |B|/avgdl = 800/200 = 4, so the length factor is 1 − 0.75 + 0.75 × 4 = 3.25. The denominator is 6 + 1.2 × 3.25 = 9.9, and the numerator is 6 × 2.2 = 13.2, giving roughly 13.2 / 9.9 ≈ 1.33.
Document A scores higher on this term (≈1.74 vs ≈1.33) despite mentioning kafka fewer times in absolute terms, because it is a quarter of the average length — a short document where a term appears at all is "more about" that term than a long document repeating it proportionally less. This is the field-length-normalisation effect from the lesson's opening bullet made arithmetic: a short field matching counts for more than the same raw count in a long one, and it is b that controls how much more (setting b toward 0 for this same example would shrink that gap, since the length factor would stop scaling with |D|/avgdl at all).
Misconceptions
- "Mentioning a term twice as often roughly doubles its contribution to the score." Only far from saturation. Near
f(t,D) = 0, more mentions matter a lot; oncef(t,D)is large relative tok1, the fraction is already close to its ceiling and another mention barely moves it — the whole point of the saturation term in the denominator. - "A longer document is always penalised for length, so short content should win by default." Length normalisation discounts a term's relative frequency, not the document's relevance outright — a long document that is thoroughly about the query terms (many matching terms, not just one repeated) can still outscore a short one, because BM25 sums the per-term score across every matching query term, and
bonly controls how strongly length enters that per-term calculation, not whether a long document can win.
Sources
- Stephen Robertson and Hugo Zaragoza, "The Probabilistic Relevance Framework: BM25 and Beyond", Foundations and Trends in Information Retrieval, 2009 — the canonical description of the BM25 formula and its derivation.
- Christopher D. Manning, Prabhakar Raghavan and Hinrich Schütze, Introduction to Information Retrieval — vector-space TF-IDF scoring and probabilistic ranking, for the contrast with BM25.
- Elasticsearch/Lucene documentation on the practical scoring function (
BM25Similarity) and index-levelsimilaritysettings.