Skip to main content
SEARCH
Andrei Moise · Search Notes

How search works

How a search engine finds pages and puts them in order: inverted indexes and BM25, click signals, knowledge graphs, dense vectors, hybrid fusion, NDCG, and RAG.

  • Three dimensions of search intent. Good relevance combines Content understanding (matching keywords, language patterns, and attributes), User understanding (each searcher's preferences and history), and Domain understanding (what words, phrases, and entities mean in your own domain).
  • Reflected intelligence. Every query, click, and conversion feeds back into the search engine. Instead of hand-writing rules forever, the system learns domain language and ranking weights from real traffic. It comes in four families: popularized (signals boosting), personalized (collaborative filtering), generalized (learning to rank), and knowledge graph learning (related terms and misspellings from query logs). See the table in §3.
  • Four architectural layers. Sparse lexical retrieval (BM25), domain query understanding (knowledge graphs), learned ranking (signals, personalization, LTR), and neural retrieval (dense vectors, hybrid fusion, RAG).
§0 · Primer (Skip if you already know this)

From raw strings to postings and vectors

A search engine does not scan your docs word by word at query time. At index time, an analyzer typically lowercases each document, strips punctuation, and may drop stop words and stem terms. The same analyzer runs on the query, so both sides produce the same terms. The engine then builds an inverted index where each term points straight to the list of documents containing it.

Eight ideas the rest of the page is built on

§0.a · Inverted index
A lookup table from words to pages. AND and OR are just set math.

The engine never reads pages at search time. It looks each word up and gets back the list of pages that contain it. AND keeps pages in both lists. OR keeps pages in either.

word A
word B
rule
§0.b · Diminishing returns
The 10th mention shouldn't count like the 1st. A curve that bends and flattens.

Raw counting gives every repeat the same value, so spam wins. A saturating curve gives the first few mentions most of the credit and later ones almost none. BM25 (§2) is built on this.

§0.c · Rarity is information
Rare words tell you more. Common words tell you almost nothing.

If a word is on almost every page, finding it on one more page says nothing. If it's on 3 pages out of 1,000, it's a strong clue. That's IDF: weight = log(pages ÷ pages with the word).

§0.d · Precision vs. recall
Show more, find more, but get messier. You can't max both.

Precision: of what you showed, how much was right. Recall: of everything right, how much you showed. Moving the cutoff down a ranked list trades one for the other.

§0.e · Position matters
A great result at #8 is worth less than at #1. Ranking metrics discount by position.

People (and metrics like NDCG, §11) care most about the top. A common discount is 1 ÷ log₂(rank + 1): rank 1 counts fully, rank 2 counts 63%, and it keeps shrinking.

§0.f · Small numbers lie
2 clicks out of 3 views isn't a 67% page. Start from a sensible guess.

With few views, a click rate jumps all over the place. Smoothing starts from a prior guess (25%) and only moves away as evidence piles up (Beta smoothing, §5). This page's true click rate is 40%.

§0.g · Meaning as a place
Similar meanings sit close together. Search = find the nearest points.

An embedding turns text into a point. Phrases that mean the same thing land near each other, even with no shared words. Vector search (§7) returns the points nearest to your query.

§0.h · Quantization in one line
Snap every number to one of a few levels. b bits = 2b levels.

To save memory, store each number as the nearest of a few allowed values. Each extra bit doubles the levels and halves the gap, so the largest possible error (half the gap) halves too (§9).

bits
Go deeper · 3 more notes
  • Stemming vs. lemmatization. Stemming chops suffixes with simple rules (retries becomes retry, running becomes run; exact output depends on the stemmer). Lemmatization uses a dictionary so better maps to good, at higher CPU cost. Stemming adds false positives. Skip it when you need precision, such as normalizing queries for click signals or matching exact entities. For documents, a common fix is two fields, one stemmed and one unstemmed, with the unstemmed one boosted higher.
  • Stop-word pitfalls. Dropping common words like the or in shrinks the index, but breaks queries like "to be or not to be" or "Vitamin A". Modern BM25 engines often keep stop words and let low IDF down-weight them. Low IDF fixes ranking, not matching. With an OR query, "the hobbit" still pulls in every page that contains the once the hobbit pages run out. Pair kept stop words with min match (mm, §1).
  • Distributional semantics. Words that appear in similar document neighborhoods share meaning. That single observation powers both knowledge graphs (§4) and dense embeddings (§7).
DEMO 0.1 Analyzer → Inverted Index Lookup
Type a query · watch it become terms and postings
Presets:
1. Analysis Pipeline 3 index terms
2. Inverted Index Postings 11 postings hit
Term DF Postings [doc: tf]

Sparse vectors: direction vs. length

Cosine similarity looks at the direction of two vectors and ignores their length. The dot product multiplies coordinates out so length counts too.

  • Sparse vectors. TF-IDF and BM25 give every word its own slot, so almost every slot is zero. In a small apple juice example, the vocabulary has 48 slots and the query fills only 2 of them; engines store only the non-zero entries.
  • Direction. Cosine asks whether a document uses the query's words in the same proportions.
  • Length. The dot product also grows when a document repeats those words more often.
Vector Similarity Primitives
$$\cos(\mathbf{q}, \mathbf{d}) = \frac{\mathbf{q} \cdot \mathbf{d}}{\|\mathbf{q}\|\,\|\mathbf{d}\|} \qquad\qquad \mathbf{q} \cdot \mathbf{d} = \sum_i q_i\, d_i$$
Doc A = draggable vector (green) Doc B = draggable vector (blue) θ = angle between them (0° means identical proportions)
DEMO 0.2 Drag Vector Tips: Cosine vs. Dot Product
Drag a vector tip · watch cosine hold while dot grows
Presets:
2D Term Space (apple vs. juice)
Term Counts & Vector Norms Identical direction
Cosine Similarity 1.000 Direction only (length-invariant)
Dot Product (A · B) 15.0 Grows with vector length
Angle θ 0.0° 0° = parallel · 90° = disjoint
  1. Start. Doc A (2, 1) and Doc B (6, 3) point in the exact same direction. Cosine is 1.000 while the dot product jumps to 15.0 because Doc B is three times longer.
  2. Check "Normalize to unit circle". Both vectors snap to length 1. Dot product and cosine now show the exact same number, which is why vector databases normalize at index time.
  3. Click "Orthogonal". Doc A is all apple and Doc B is all juice. They share no words, so cosine and the dot product both fall to 0 and the angle opens to 90°.

Ranking with cosine vs. dot product

The difference matters once there is a query. Take the query "apple juice" and two pages: Doc 1 is a lunch order that mentions apple juice once, and Doc 2 is a product page that says apple 3 times and juice 4 times.

DEMO 0.3 Rank Two Pages for "apple juice"
Change the word counts · watch cosine and dot product pick different winners
1×
1×
3×
4×
query vs. Doc 1 and Doc 2 · word counts
who ranks first? · two measures
  1. Start. Doc 1 has exactly the query's proportions: cosine 1.00, dot product 2. Doc 2 is slightly off (cosine 0.99) but much longer (dot product 7). Cosine ranks Doc 1 first; the dot product ranks Doc 2 first.
  2. Set Doc 2 · apple to 4. Now Doc 2 has the query's proportions too: cosine 1.00 for both, and the dot product climbs to 8.
  3. Set Doc 2 · apple to 0 and juice to 5. Doc 2 drops "apple" completely. Cosine falls to 0.71, yet the dot product still prefers it, 5 to 2. Raw repetition wins again, the same problem BM25 caps with k₁.
■ Takeaway · Next §1

An inverted index finds candidate documents in microseconds, and vector math scores how closely they align. Before scoring anything, the engine has to separate eligible documents from ineligible ones.

Next: §1 Match vs. rank
Part 1 Words Find pages that contain the query, then score how well the text matches.
§1 · Eligibility vs. Ordering

Matching vs. ranking

Every search request runs in two steps. Matching decides which pages are eligible at all, which sets result counts and facets. It also keeps the work small, since scoring a few hundred matches is far cheaper than scoring every page. Filters and the query do different jobs. A filter like category = docs only removes pages; the query removes pages and scores the survivors.

Match RuleWhat Qualifies
Exact phraseOnly pages containing the exact sequence of words
All words (AND)Pages with every query word, in any order
Min match (mm)Pages with at least some share of the words, such as 2 of 3 (mm=2) or 75% (mm=75%)
Any word (OR)Pages with at least one word; BM25 usually ranks pages that match more of the words higher
DEMO 1.1 The Two-Stage Candidate Funnel
Switch the match rule · watch the funnel shrink
Match rule:
Query:
50% → 1 of 2
Candidate Funnel 6 / 8 survive
All 8 Docs (Eligibility & Score) #1: d1
Indexed Corpus 8 Total pages in index
Matched & Filtered 6 Binary yes/no gate
Filtered Out 1 Matched text, failed filter
  1. Start on "Any word (OR)" with Filter checked. Seven pages match at least one word. The filter category = docs removes the changelog (d4) without affecting any score, so six survive.
  2. Switch to "All words (AND)". Only pages containing both econnreset and retry survive. Precision goes up, recall drops.
  3. Switch to "Exact phrase". Zero pages contain the literal two-word phrase "econnreset retry", even though d1 solves the exact problem. That is why phrase queries belong in a boost clause rather than a hard requirement.
  4. Click the 4-word query, then "Min match (mm)". AND keeps only 2 docs, while OR lets in pages that share a single word. At mm = 50% a page needs 2 of the 4 words. At 75% it needs 3, which keeps the focused pages and drops the weak ones. Drag the slider to feel the dial between AND and OR.
  • Minimum match is the real-world default. Pure AND often returns too little for long queries, and pure OR floods results with one-word matches. Solr calls the setting mm, and Elasticsearch and OpenSearch call it minimum_should_match. It takes a count (2) or a percent (75%).
  • Step functions. One rule can change with query length. mm=2<-30% 5<3 means: with 1 or 2 words, all are required; with 3 to 5 words, up to 30% can be missing (rounded down, so 3 words still need all 3); with 6 or more words, at least 3 must match. Short queries stay strict, long ones get room.
Production note: why filters are cached bitsets in Lucene / Elasticsearch

In Elasticsearch and OpenSearch, putting category = docs inside a filter clause (instead of a must clause) skips scoring completely. Once a filter is used often, Lucene caches its matching document IDs as a compact bitset, and later queries reuse it instead of re-running the filter.

If you accidentally put a filter in a scoring clause, you waste CPU scoring every document on category:docs, lose filter caching, and pollute your relevance scores with metadata noise.

■ Takeaway · Next §2

Matching gives you the eligible set. The first textbook formula people try for ranking it, TF-IDF, breaks on two common docs patterns.

Next: §2 From TF-IDF to BM25
§2 · Scoring Text

From word counts to BM25

TF-IDF multiplies how often a term appears in a document (TF) by how rare that term is across the corpus (IDF). Naive TF-IDF (raw counts, no length handling) is mostly a teaching exercise now, and two failure modes explain why. (Lucene's older classic scorer already softened repeats with √tf and added a length norm, so the raw version here is the naive baseline.)

TF-IDF (idf × raw tf)BM25 (idf × capped tf ÷ length)
Repeats never plateau: 50 mentions ≠ 50× relevantSaturation controlled by k₁
Long docs win by default: more words, more matchesLength normalization controlled by b
DEMO 2.1 Same Query, Two Scorers: TF-IDF vs. BM25 ("econnreset retry")
Drag the FAQ's bar · watch TF-IDF crown the wrong page
Scenarios:
14
1400w
TF-IDF · raw count × rarity
BM25 · capped count × rarity, length-adjusted
IDF · how rare is the word? (out of 8 pages) · ln(1 + (N − df + 0.5)/(df + 0.5)), used by both scorers
TF-IDF #1 Stuffed FAQ Wrong page crowned #1
BM25 #1 Fixing ECONNRESET Saturation + length norm hold
IDF Weight 0.693 df = 4 of 8 pages
  1. Start on "Keyword-stuffed FAQ". The query is econnreset retry, and both charts list the same pages in the same order. TF-IDF (left) crowns the thin FAQ: its 14 mentions of econnreset count 14 times, even though it never says retry. BM25 (right) caps the repeats, so "Fixing ECONNRESET", which has both words, stays #1.
  2. Drag the handle on the FAQ's bar. On the left, the bar follows your mouse: every mention adds the same amount. On the right, the FAQ's bar barely moves once it passes a handful of mentions.
  3. Click "Long changelog". A 2,000-word changelog mentions both words just by being long, so it wins under naive TF-IDF, which never looks at length. BM25 shrinks it for being much longer than average.
  4. Drag the dot on the IDF curve. A word in 1 of 8 pages gets IDF = 1.79. A word in all 8 collapses to 0.06.

BM25 under the hood: saturation and length

Someone is going through your docs for ECONNRESET. One page has it 5 times and is twice the length of the average page. Each part of BM25 has its own job on those 5 mentions:

  • TF (term frequency). The page has ECONNRESET 5 times. Raw TF-IDF gives that a value of 5.
  • IDF (rarity). An error code on a few pages is worth more than a common word like connection. It multiplies every curve by the same constant.
  • k₁ (saturation). Caps what repeats are worth. At k₁ = 1.2, the weight can never cross k₁ + 1 = 2.2.
  • b (length penalty). A long page has more chances to repeat any word. At b = 0.75, a 2× longer page scores 13% less than an average page with the same 5 mentions.
BM25 Scoring Formula (Textbook Form)
$$\text{BM25}(q, d) = \sum_{t \in q} \underbrace{\text{IDF}(t)}_{\text{rarity}} \cdot \frac{\text{tf}(t,d)\cdot(k_1 + 1)}{\text{tf}(t,d) + k_1 \cdot \left(1 - b + b \cdot \frac{|d|}{\text{avgdl}}\right)}$$
k₁ = TF saturation speed (ceiling is k₁ + 1) b = length penalty (0 = ignore length, 1 = full penalty) IDF(t) = ln(1 + (N − df + 0.5) / (df + 0.5)), the rarity curve above
DEMO 2.2 BM25's Two Knobs: Saturation (k₁) and Length (b)
Drag the dots · watch repeats hit the ceiling
Presets:
1.2
0.75
weight vs. mentions (tf)
weight vs. page length (× average)

Corpus Order ("econnreset retry") #1: d1
Raw tf → BM25 weight 1.55 For the page you're dragging
Ceiling (k₁ + 1) 2.20 No single word's TF weight can reach this
vs. Average-Length Page -13% Effect of length × b
  1. Start on "Lucene default". The page has 5 mentions and is twice the average length. BM25 gives it a weight of 1.55 instead of 5. Both dots sit at the same height, because both charts show the same weight.
  2. Drag the top dot to tf = 20. Four times the mentions, yet the weight only climbs to 1.99, just under the 2.2 ceiling.
  3. Drag the bottom dot to 1.0×. At average length the same 5 mentions are worth 1.77, so the long page was losing 13%.
  4. Click "Ignore length (b=0)". The length curve goes flat. Page length stops mattering, and with no length penalty the 1,400-word changelog already takes #1 in the live list.
  5. Click "Weak saturation". The ceiling rises to 6.0, repeats keep paying off for longer, and the changelog's lead widens.
  • Default to BM25 for lexical search. It is the baseline in Elasticsearch, OpenSearch, Lucene, and most RAG stacks.
  • Use it alongside embeddings, not instead of them. BM25 wins on exact matches (IDs, error codes, names, specialist jargon). Dense retrievers win on paraphrase and meaning. The common setup today is both together (hybrid search, §8), followed by a reranker.
  • Start with k₁ ≈ 1.2 and b ≈ 0.75. Tuning matters most when documents are very short or very uneven in length. Don't guess: grid-search k₁ and b on a small labeled set and keep the pair with the best NDCG@10 (the headline metric public benchmarks like BEIR report, §11).
Production gotcha: why Elasticsearch & Lucene scores look smaller than the textbook

Since version 8, Lucene (and therefore Elasticsearch, OpenSearch, and Solr) drops the constant (k₁ + 1) factor from the numerator because it is identical for every document matching a query. Dropping it never changes the ranking order, but it caps the TF component at 1.0 instead of k₁ + 1.

Expect different absolute scores in other tools. Python's rank_bm25, for example, keeps the (k₁ + 1) factor, defaults to k₁ = 1.5, and uses a slightly different IDF. Lucene also stores page length approximately, and Elasticsearch computes statistics per shard. Compare rankings, not raw scores. This page's explain trees show the textbook form, with TF parts up to k₁ + 1.

Field boosts, phrase boosts, and reading the score

Real pages have more than one field. A match in the title usually means more than a match deep in the body, so engines score each field with its own BM25 and multiply it by a field boost, such as qf = title^3 body^1. Phrase boosts (pf, pf2, pf3) add points when query words sit next to each other, without throwing out pages where they don't. When a ranking looks wrong, the engine's explain output shows every number that went into a score.

  • Field boosts (qf). title^10 description^2.5 makes a title match worth 10× and a description match worth 2.5×. Each field keeps its own term counts and its own average length. By default Solr takes the best-scoring field for each word (dismax; a tie setting blends in the others). The demo below simply adds the fields, like Elasticsearch's most_fields.
  • Phrase boosts (pf, pf2, pf3). pf boosts the full phrase, pf2 every two-word pair, and pf3 every three-word run. They only add score. They never remove a page.
  • The explain tree. For each matched word, the engine prints the boost, the IDF (with n and N), and the TF part (with freq, k1, b, dl, avgdl), then adds them up. Reading it is the first step in any relevance bug hunt.
DEMO 2.3 Field Boosts, Phrase Boosts & the Explain Tree
Click a result · read why it scored that way
Query:
Presets:
0
1
0
Ranked Results #1: d1
explain: d1 BM25 per field

            
  1. Start on "connection reset" with "Body only". Pages are ranked by body BM25 alone. Click a few rows and read their explain trees.
  2. Click "qf title^3 body^1". d2 ("HTTP Keep-Alive & Connection Pools") has connection in its title, so its title score is tripled and it moves up.
  3. Click "+ pf2^2". Pages where connection and reset sit side by side get a phrase bonus. The explain tree shows it as its own line.
  4. Switch to "retry timeout". No page has that exact pair, so the phrase boost adds nothing. Title boosts now decide between d3 (retry in title) and d6 (timeout in title).

Simplified for the demo: a phrase hit adds pf2 × (IDF(word₁) + IDF(word₂)). Real engines count how often the phrase occurs (its own TF) and use the summed IDF of its words. In this demo, stop words are dropped before checking that words are next to each other.

■ Takeaway · Next §3

IDF rewards rare words, but raw counts let keyword stuffing and long pages win. BM25 fixes both with k₁ (saturation) and b (length). Field and phrase boosts decide which matches count most.

Next: §3 Business factors and clicks
Part 2 People Learn from what users click, type, and skip.
§3 · Beyond Text

Business factors, click signals, and personalization

Most teams stop at "BM25 (plus embeddings) ranks my results". On its own, that falls far short for many search tasks. A news site cares how fresh an article is, a restaurant search cares how close it is, a shop cares about popularity, price, and return rate. Engines let you blend these into one score with functions, such as a reciprocal decay on age (recip) and a distance function (geodist). In domains like news, local, and shopping, blending in these factors often beats text-only BM25 by a wide margin.

Blended Score (each factor scaled to 0 to 1 first)
$$\text{score}(d) = w_{\text{text}} \cdot \frac{\text{BM25}}{\text{max}} + w_{\text{fresh}} \cdot \frac{1}{1 + \text{days}/7} + w_{\text{near}} \cdot \frac{1}{1 + \text{km}/50} + w_{\text{pop}} \cdot \frac{\log(1+\text{clicks})}{\log(1+\text{max clicks})}$$
Scale first = BM25 is unbounded, so put every factor on a 0 to 1 scale Reciprocal decay = a 1-week-old article scores 0.5 on freshness Weights = a simple news blend uses 25% each
DEMO 3.1 News Search for "basketball": Text + Freshness + Nearby + Popularity
Drag the weights · watch fresh, local news rise
Presets:
1.00
0.00
0.00
0.00
Ranked Articles (bar = where the score comes from) #1: n1
#1 ArticleBasketball: The Complete…Top of the page
Its Age4.0 yr oldNews readers want fresh
Its Distance4,000 kmFrom the reader
  1. Start on "Text only (BM25)". The winner is a 4-year-old rules guide from 4,000 km away, followed by a history piece. Both use "basketball" a lot, and neither is news.
  2. Click "News site: 25% each". This is a simple, even blend. Last night's local high school final jumps to #1: fresh, nearby, and popular. The rules guide falls to #5.
  3. Click "Trending". With no weight on distance, the pro trade-deadline recap (5,200 clicks, 2 days old) takes #1.
  4. Drag "Text (BM25)" up and the other weights down. The blue slice grows in every bar, and once the other weights are near 0 the old, wordy articles win again.

Signals boosting: adding vs. multiplying, and time decay

Click logs, saves, and resolved tickets tell you which pages help people. Two choices control how popularity interacts with BM25: whether you combine them by addition (+) or multiplication (×), and how quickly old clicks expire under half-life decay.

Signals boosting is only the first of four families of reflected intelligence built from the same click logs: three ranking models, plus knowledge graph learning. Each learns a different kind of relevance, and each fails in a different place. That is why real stacks combine them instead of picking one.

ModelKind of RelevanceWhat It LearnsWhere It Breaks
Signals boosting (§3)PopularizedWhich docs people pick for this exact queryQueries with few or no clicks, and brand-new docs
Collaborative filtering (§3)PersonalizedWhat this user tends to like, from their past actionsNew users and new items (cold start)
Learning to rank (§6)GeneralizedWhich features make any doc relevant (title match, recency, …)Needs good features and training labels
Knowledge graph learning (§4)SemanticRelated terms, synonyms, and misspellings, mined from query logsA smaller win today. The quick win is crowdsourced misspellings (users retype toochpad as touchpad)
  • Head, torso, and tail queries. A few head queries arrive thousands of times, torso queries arrive now and then, and the long tail of rare queries may arrive once. Boosting only works where clicks pile up, so it helps the head and leaves the tail untouched. LTR is what carries the tail.
  • Weighting user actions. Not all signals carry the same intent. In commerce search, an example starting point is click = 1, add-to-cart = 10, and purchase = 25 (tune them per site); in docs search, a copy-code event or "helpful" vote outweighs a raw page view.
  • Anti-spam: one vote per user. When you aggregate signals, group by user so each user counts once per query, document, and signal type, across the whole time window, not just one session. A per-session rule lets a bot start new sessions and vote again. When you keep one signal per user, pick whether their first or most recent signal wins. "Most recent" lets their vote change over time. Decide it together with your time decay, since decay ages each vote by its timestamp.
  • The lagging indicator trap. Signals only measure what users saw in the past. Half-life decay prevents last year's popular page from blocking newer, better answers.
Time Decay & Boosting Modes
$$w(s) = w_t \cdot 2^{-\text{age} / \lambda} \qquad\qquad S_{\text{add}} = S_{\text{BM25}} + w \cdot p(d) \qquad S_{\text{mul}} = S_{\text{BM25}} \cdot (1 + w \cdot p(d))$$
λ = half-life in days (weight halves every λ days) Additive (+) = fixed bonus, can overpower a page's weak text match Multiplicative (×) = scales proportionally with text relevance p(d) = popularity: log-scaled, decayed clicks on a 0 to 1 scale
DEMO 3.2 Adding vs. Multiplying a Popularity Boost (and Old Clicks Fading)
Raise the boost · watch + and × disagree
Query:
4.0
BM25 + w·pop · additive
BM25 × (1 + w·pop) · multiplicative
Half-life:
click weight left vs. age · dots = each page's clicks
Additive (+) #1 Getting Started Flat bonus, ignores text match
Multiplicative (×) #1 Fixing ECONNRESET Bonus scales with text match
A Click's Weight After 6 Months 2% Half-life 30 days
  1. Start on the rare query at w = 4. Both charts show the same pages in the same order. Each bar is the text score (blue) plus the popularity bonus (amber). On the left, "Getting Started" barely matches the query (BM25 0.6), yet its flat bonus puts it at #1. On the right, its bonus is a fraction of a tiny score, so the real fix stays on top.
  2. Drag w down to 3. The additive bonus shrinks and "Fixing ECONNRESET" wins again. With "+", the result depends on picking just the right weight.
  3. Switch to "Common: api error". When text scores are close, popularity should break the tie, and both models lift the popular "Rate Limit (429)" page.
  4. Go back to the rare query and click "News: 1 day". Every page's clicks are days old, so the bonuses shrink a lot and the text match decides. Click "Slow catalog" and old clicks keep almost all their weight (94% after six months).
Production note: query-time vs. index-time payload boosting

Query-time boosting runs a lookup in a signals store and appends boosted doc IDs to the main query. Index-time payload boosting writes the top queries and their weights directly onto each document, so there is no signals-store lookup and no huge query string at search time.

One boost, two searches

The clearest way to see the difference: keep the same two pages and run two searches. The rare word ECONNRESET gives big BM25 scores; the common word connection gives scores ten times smaller, in the same ratio. The Error Code List matches better; the Troubleshooting Guide is more popular (popularity 0.9 vs 0.2).

DEMO 3.3 Same Two Pages, Two Searches: Plus vs. Times
Drag the boost weight · watch "plus" give two searches two answers
0.50
who leads, as the boost grows · above 0 = Error Code List ahead
ECONNRESETconnection plus times
  1. Start at w = 0.5. Times: the Error Code List wins both searches. Plus: it wins ECONNRESET (12.10 vs 9.45) but loses connection (1.30 vs 1.35). The same added bonus is tiny next to big scores and huge next to small ones.
  2. Raise w to 1. Times: the Troubleshooting Guide now wins both searches, so the two searches still agree. Plus: they still disagree.
  3. Watch the green line. Under "times" both searches sit on exactly the same line, because multiplying keeps each search's score ratio. A multiplied boost affects every search the same way; an added boost has to be tuned to each search's score range. The flip side: push a multiplied boost too high and popularity swamps relevance.

From a raw signals log to boosts

Signals start with a log. A good format is one flat log with five fields per event: query_id, signal_time, user, type, and target. Each search gets its own query_id. Its first event is the query (target = the text typed), then results (target = the exact ordered list shown). Every later click, copy, or vote carries the same query_id, so you always know which search led to it and what the user saw. User Behavior Insights (UBI), an open-source format that started in OpenSearch and now works with other engines, does the same job.

  • Log what was shown, in order. Without the ordered results event you can't tell a skipped result from an unseen one, so click models (§5) and position-bias fixes become impossible later.
  • Normalize the query text first. ECONNRESET, econnreset, and " EconnReset " are one intent. Lowercasing and trimming spaces merges their counts. Avoid stemming here, since it can merge different intents.
  • Count negative signals too. A boost can be positive signals minus negative ones. Skips, "not helpful" votes, and product returns (tied back to the purchase's query_id) all push a result down.
  • One vote per user. Group by user before summing, so one bot can't outvote everyone (see the anti-spam note above).
DEMO 3.4 Raw Signals Log → Boosts for "econnreset"
Turn on each fix · watch the bot lose
Fixes:

Weights: click = 1, copy_code = 10, helpful = 25, not_helpful = −20.

Raw Log (5 fields per event) 54 events
Boosts for This Query key: "econnreset"
Boosted to #1d5d5 is the keyword-stuffed FAQ
Events Counted34After the fixes you turned on
  1. Start with every fix off. The keyword-stuffed FAQ (d5) gets the top boost, +30. All of it comes from one bot (u9) clicking it 30 times.
  2. Turn on "One vote per user". The bot now counts once. d1 (the real fix) takes #1 with +26.
  3. Turn on "Normalize query text". Searches typed as ECONNRESET, " EconnReset ", and Econnreset now count too. d1 climbs to +48.
  4. Turn on "Count negative signals". Two users marked d5 "not helpful", so its boost drops to −37 and it gets pushed down.

Personalized search and category guardrails

  • Personalization with guardrails. Collaborative filtering (R ≈ U · Vᵀ) and user embeddings lift preferred topics, but need category guardrails so past clicks on billing do not hijack a network-error search.
DEMO 3.5 Collaborative Filtering (U · Vᵀ) & Guardrails
Switch users · watch the guardrail block off-topic boosts
User:
Query:
#1 Personalized Result Fixing ECONNRESET BM25 + U·Vᵀ affinity
Active Strategy Guarded CF Protects specific queries
Cold-Start Rule BM25 Only No user history yet
  1. Pick "Billing Admin", then "econnreset". With the guardrail on, the network-error pages keep the top spots. The user's billing history can't boost off-topic pages for a specific query.
  2. Untick the guardrail. "Reset Billing Admin Password" jumps to #1. Its text match is weak, but this user's billing history outweighs it. That is personalization hijacking the query.
  3. Switch to "reset". Now the query really is ambiguous, so letting each user's history pick the meaning helps: billing users get the billing reset, Node engineers get the connection reset.
  4. Pick "New User". There is no history, so the ranking falls back to plain BM25.
■ Takeaway · Next §4

Multiplicative boosts keep rare queries grounded in text relevance, half-life decay stops stale clicks from sticking forever, and guardrails keep personalization on topic. Next: reading the query itself.

Next: §4 Query understanding
§4 · Query Understanding

Query interpretation and semantic knowledge graphs

When someone searches top redis cache guide or postgres driver timeout, treating every word as a plain keyword throws away structure. A semantic query pipeline runs four stages: parse entities and trigger words with an FST tagger, enrich them via a Semantic Knowledge Graph (SKG) built from your inverted index, transform triggers into filters and boosts, and search.

  • Query log mining. Users teach you your domain vocabulary when they reformulate failed queries. Mining query pairs surfaces domain synonyms (socket hang up and ECONNRESET), misspellings, and multi-word phrases automatically.
  • Two-level sense disambiguation. An ambiguous word like driver cannot be expanded blindly. A two-level SKG traversal first identifies the category (databases vs. golf or rideshare) and then expands terms only inside that subgraph.
  • Semantic functions. Trigger words like top, near, or under $50 do not belong in the keyword query. The transform step converts them into rating boosts, geospatial geofilt clauses, or range filters.
Go deeper · 2 more notes
  • Explicit triples and Hearst patterns. Alongside statistical SKGs, Open Information Extraction parses sentences like "databases such as Postgres" into explicit RDF triples (Subject, Predicate, Object) stored in a sidecar collection for exact taxonomical hierarchies.
  • Knowledge modeling spectrum. Separate alternative labels (deterministic replacements for acronyms and typos), synonyms (broader recall expansion), and ontologies/taxonomies (structural is_a class hierarchies) instead of dumping everything into one synonym file.
DEMO 4.1 4-Phase Pipeline & SKG Relatedness
Pick a query · watch it get parsed, enriched, rewritten
Queries:
1. Parse (FST Tree) → 3. Transform query_tree
Transformed Engine Query
2. Enrich: SKG Relatedness [-1, +1] Context: network_error + nodejs

Where SKG relatedness scores come from

Each [-1, +1] score above comes from a statistical test on document sets. Take every document that matches the foreground query (say pain). Count how often a candidate word (say advil) shows up there, and compare that with how often it shows up in the background (the whole index). If it appears far more often than chance, the two are related.

SKG Relatedness (z-score, then squashed to [−1, 1])
$$z(x) = \frac{|D_x \cap D_{fg}| \;-\; |D_{fg}| \cdot P_x}{\sqrt{|D_{fg}| \cdot P_x \,(1 - P_x)}} \qquad\qquad P_x = \frac{|D_x \cap D_{bg}|}{|D_{bg}|}$$
D_fg = docs matching the foreground query (e.g. pain) P_x = chance a random background doc contains x z → [−1, 1] = a sigmoid squashes the score; 0 means "no link"
  • Reading the score. Near +1: strongly related (advil for pain). Near 0: no link, which is where stop words like the land, because they appear everywhere. Near −1: the word belongs to a different domain and avoids these docs.
  • Noise floor (min_occurrences). A word seen in only one or two matching docs can score high by luck. So you set a minimum number of docs a word must appear in before it gets scored (the setting's name varies by engine). Always use more than 1. Start with a small threshold and tune it on your own data.
  • The forward index makes the hop possible. The inverted index maps term → docs. To ask "which words appear in these docs?", the engine needs the reverse, doc → terms. That forward index is what search engines already use for facets, and you turn it on per field with doc values. One SKG hop is: query → doc set (inverted index) → terms in those docs (forward index) → score each term.
  • Works best on overlapping text. SKGs need words to repeat across many docs. Forums, tickets, and reviews work well. A wiki with one page per topic gives weak scores.
DEMO 4.2 How Related Is This Word to "econnreset"?
Pick a word · watch "more than chance" become a score
Candidate word:
0
how often the word appears · background vs. foreground
z-score → relatedness (squashed to −1…+1)

A toy forum of 10,000 posts; 400 of them mention "econnreset" (the foreground). The squash used here is 2·sigmoid(z/4) − 1; engines use their own sigmoid, same idea.

  1. Start on "keepalive". It's in 6% of all posts but 38% of the econnreset posts: over 6× what chance predicts. That's a huge z-score, so relatedness is close to +1.
  2. Click "the". It's in almost every post, inside or outside the foreground, so it's exactly at chance: z ≈ 0, relatedness ≈ 0. High co-occurrence alone means nothing.
  3. Click "invoice". It shows up far less than chance in econnreset posts. It belongs to a different topic, so the score goes negative.
  4. Click "kubeproxy (fluke)", then raise min_occurrences to 3. A word seen in just 2 posts looks clearly related (relatedness about +0.6) purely by luck. The noise floor removes it.

Walking the graph: one hop, then two

A semantic knowledge graph is not stored anywhere. Each edge is computed on the fly: take the posts that contain a word, then score every other word by how much more often it appears there than chance (the relatedness score above). Click a word to make it the new center. A second hop narrows the posts to those containing both words, which is how one meaning of an ambiguous word gets picked.

DEMO 4.3 Walk a Knowledge Graph Built from 4,000 Posts
Click a word to hop · turn on hop 2 to split meanings
Start at:
path: econnreset

Line thickness and the number on each line = relatedness (−1 to +1), computed live from a toy forum of 4,000 posts. Colors are topics: network errors, databases, golf, rideshare, and gray for billing or for words with no topic (like "the"). A word with several meanings takes the color of its most common topic. Only words seen in at least 5 posts with relatedness ≥ 0.2 are drawn. Dashed lines are the second hop.

  1. Start on "econnreset". Every neighbor is a network-error word (socket, retry, keepalive…), each above +0.9. Words like "the" never appear: they are in almost every post, so their relatedness stays near 0 (about −0.3 here, just chance noise), below the 0.2 cutoff.
  2. Click "driver (3 meanings)". Its neighbors come from databases, golf, and rideshare at once. Expanding "driver" into all of them would send a database search to golf pages.
  3. Tick "Show hop 2". Each branch now uses only the posts that contain both words. From "postgres" the second hop stays in databases, from "tee" it stays in golf. That is the two-level traversal: pick the meaning first, then expand.
  4. Click any neighbor to hop to it, and "Back" to return. The path above the graph shows your walk. Every edge is recomputed for the new center.

Learning spelling corrections from query logs

An off-the-shelf spellchecker picks the nearby word that appears most in your documents. For example, the typo moden gets "corrected" to modes, model, or modern, when shoppers clearly meant modem. Your query log knows better. Rare words that look like common searched words are probably typos of them.

  • Step 1: split by quantile. Count how many distinct users searched each word. Words in the bottom slice (the bottom 20% works well on a big log) become typo candidates. Words in the top slice (top 20%) become possible corrections. Quantiles adapt to any log size, unlike fixed counts.
  • Step 2: match by edit distance, scaled by length. Only compare words with the same first letter. Shorter words get fewer allowed edits: under 8 letters, exactly 1 edit; 8–10 letters, up to 2; 11 or more, up to 3.
  • Step 3: pick the most-searched match. If several corrections fit, the one more users searched wins.
DEMO 4.4 Learn Spelling Fixes from a Query Log
Move the cutoffs · watch right vs. wrong fixes
Edit rule:
0.55 → ≤ 34 users
0.65 → ≥ 354 users
Query Log users per word
Learned Corrections typo → fix
Right Fixes 9 Typo mapped to its real word
Wrong Fixes 0 A real word changed, or a typo fixed to a typo
Missed Typos 5 Typos left unfixed
  1. Start (0.55 / 0.65, scaled by length). 9 typos get fixed and nothing goes wrong. The real word pull is a typo candidate, but it is left alone. Both idempotent typos are missed, because idempotent (210 users) is below the correction cutoff.
  2. Lower the correction cutoff to 0.60. idempotent becomes a correction, and both of its typos get fixed: 11 right.
  3. Click "Flat: up to 2 edits". Swapped letters (tiemout, retyr) count as 2 edits under plain Levenshtein distance (Damerau distance would count a swap as 1), so now they get fixed too. But the real word pull becomes pool. That is why short words get only 1 edit.
  4. Go back to "Scaled by length" and raise the typo cutoff to 0.60. timout (48 users) is now rare enough to count as a typo and gets fixed: 12 right. On a big log, pushing the typo cutoff much higher labels common real words as typo candidates, which raises the risk of "fixing" them. In this small log the other side breaks first: set the cutoffs to 0.35 / 0.40 and the typo timout becomes a "correction", so tiemout gets mapped to another typo.
■ Takeaway · Next §5

Comparing document sets in your own index surfaces related terms and disambiguates words like driver without hand-building an ontology. Next: turning clicks into fair labels.

Next: §5 Click models
§5 · Clicks as Labels

Click models and position bias

Users click whatever sits on top, good or not, so raw clicks make biased labels. A click model corrects for position before the clicks train anything, and active learning makes sure lower results get seen at all.

  • Click model spectrum: Cascade vs. SDBN vs. Full DBN. The basic Cascade Model assumes users stop at the first click. SDBN assumes users scan down to the last click and tracks two things per result: how often it gets clicked when seen, and how often that click ends the search. Full DBN adds a "keep scanning" probability γ, since users may give up without a satisfying click, and has to be fitted with EM. SDBN is the special case γ = 1, so it can be computed by simple counting.
  • Position bias and active learning. Users click rank #1 far more often than rank #5 regardless of quality. SDBN corrects for position by counting a result as seen only if it sits at or above the last click. Results below it don't count against it, and skipped results above it count as seen but not clicked. A low-ranked item that still gets clicks is outperforming its position and deserves a boost. Active learning (for example, a Gaussian process with Expected Improvement) explores unseen docs to break self-reinforcing feedback loops.
SDBN Attractiveness & Beta Prior Smoothing
$$P(C_i=1) = P(E_i=1)\cdot P(A_i=1) \qquad\qquad \hat{g} = \frac{\alpha_0 + \text{clicks}}{\alpha_0 + \beta_0 + \text{examines}}$$
E=1 = examined (all ranks ≤ last click) Skip = examined but unclicked (negative label) W = α₀ + β₀ = prior confidence weight (the demo starts at 50; in practice, fit the prior to your own judgments)
DEMO 5.1 Why Raw Click Rate Lies: Position Bias
Send users · watch raw CTR follow position, not quality
Simulate:
Ranking:
per result · true quality vs. raw CTR vs. position-corrected

Each simulated user looks at rank 1 for sure, rank 2 with 62% chance, rank 5 with only 27%. If they look, they click with the page's true quality. "Position-corrected" = clicks ÷ how many users actually looked at that rank (in real logs you can't see who looked, so you divide by an estimated look-probability per rank). A click model called "Clicks Over Expected Clicks" uses the same idea: compare a result's clicks to what its position alone would earn.

  1. Click "+1,000 users". The best page (true quality 80%) sits at #4, and only 34% of users ever look there. Its raw CTR lands around a quarter (34% look × 80% click ≈ 27%), below page B at #2, whose true quality is only 55%. A model trained on raw CTR would learn the wrong order.
  2. Read the green bars. Dividing clicks by how many users saw each rank recovers the true quality, so the best page is back on top.
  3. Click "Best page at #1", then "+1,000 users". Same pages, same quality, but now its raw CTR shoots up just because of where it sits. That's the feedback loop: whatever is on top gets clicked, so it stays on top.
DEMO 5.2 SDBN Examination Window & Beta Smoothing
Toggle clicks to see which ranks count as seen · simulate sessions to watch the grade settle
Simulate sessions (true CTR 72%):
1
1
50
1. SDBN Click Session (Toggle Clicks) k_last rule
2. Beta(α, β) Posterior Density Prior = 25%
Last Clicked Rank Rank #3 Ranks above = examined
Raw CTR 100% Noisy at low volume
Beta Adjusted Grade 26% Pulled toward prior

Breaking presentation bias with active learning

DEMO 5.3 Greedy Exploit vs. Active Learning Exploration
Run both strategies · watch who ever sees d9 · explore uses a simple uncertainty bonus
Simulate traffic:
New Doc (d9) Rank #3 True relevance = 90%
d9 Impressions 0 Greedy starves it at 0
Online Validation Interleaving Both rankers in one list

Each query shows only the top 2 slots: #1 is always seen, #2 is seen 60% of the time. Docs are ranked by a smoothed click rate, (clicks + 1) ÷ (impressions + 4), so the unseen d9 starts at 25% and sits at #3. Greedy ranks by that rate alone, so d9 never gets shown. Active learning adds an exploration bonus, √(1.8 ÷ (impressions + 1)), that is large for docs with little data, so d9 gets tried, earns clicks, and climbs.

■ Takeaway · Next §6

Position-corrected clicks become the judgments a ranker trains on. Next: learning to rank from them.

Next: §6 Learning to rank
§6 · Machine-Learned Ranking

Learning to rank

Hand-tuning boost weights gets brittle once you have dozens of features (BM25 per field, recency, authority, personalization). Learning to Rank (LTR) trains a model such as LambdaMART on query-document feature vectors to rerank the top few hundred lexical candidates (for example, the top 500).

LTR ParadigmWhat the Model PredictsTrade-Off
PointwiseSingle relevance score per docSimple, ignores relative order between docs
PairwiseWhether doc A beats doc B: w · (x_A − x_B)Strong default; directly models ranking swaps
ListwiseWhole list order (training targets NDCG)Best alignment with search metrics (LambdaMART)
  • LTR generalizes; boosting memorizes. Signals boosting stores "for query q, doc d got clicks". A brand-new query has no row, so boosting does nothing. LTR learns patterns instead, like "a strong title match plus a recent date means relevant". Those patterns apply to any query, including one nobody has typed before. That is the "generalized relevance" in the §3 table.
  • Split train and test by query ID (qid). Never split randomly by document row. If the same query lands in both train and test, your model memorizes the query and leaks accuracy.
Go deeper · 3 more notes
  • In-engine feature logging and efi. Extract live BM25 scores and query-time external feature info (efi) directly from Elasticsearch/OpenSearch/Solr (via LTR plugins or named queries) so training features match production scoring without offline re-computation. Hosting the model inside an engine plugin is getting less common. At scale, a request is only as fast as the slowest node (tail latency), so many teams pull the top-N candidates and their features into a separate reranking service instead.
  • What production teams rerank with. Many e-commerce teams rerank with LambdaMART rather than a cross-encoder, because what matters most there is domain features like popularity, price, and PageRank (in job search, commute distance). Embedding similarity goes in as one more feature.
  • SVMRank vs. LambdaMART. SVMRank fits a linear hyperplane that orders each pair of results for a query: the more relevant doc lands on the positive side of w · (x_A − x_B). LambdaMART trains boosted decision trees on gradients weighted by how much each swap would change NDCG, so training targets NDCG even though NDCG itself can't be differentiated.
Offline vs. online metrics, and splitting data by query

Offline vs. online metric divergence: Offline NDCG gains often miss online A/B conversion lifts because of UI layout and presentation bias. Team-draft interleaving mixes results from ranker A and ranker B into one list, so the same users see both and their clicks show which ranker they prefer, without splitting traffic into A/B buckets.

Query-level data splitting: Partition labeled datasets strictly by qid (for example 75% train, 20% test, 5% holdout) so the same query's documents never appear in both train and test. To keep paraphrases from leaking too, group near-duplicate queries before splitting.

Pairwise Learning to Rank trainer

Before training a linear model, put every feature on the same scale. A release_year near 2010 and a title_bm25 between 0 and 8 can't be compared raw: the big numbers drown out the small ones, and a linear model like SVMRank finds a bad dividing line. The fix is the z-score. Each value becomes "how many standard deviations above or below the average is this?"

Feature Normalization (z-score)
$$z = \frac{x - \mu}{\sigma}$$
μ = the feature's average in the training data σ = its standard deviation Example = mean year 1990, σ = 22 → 2012 becomes +1.0, 1968 becomes −1.0
  • Which models need it. Scaling matters for some models: linear ones like SVMRank, and neural nets. Tree models like LambdaMART split on raw values (if title_bm25 > 2 …), so scaling doesn't change what they learn.
  • Ship μ and σ with the model. Live queries must be scaled with the training μ and σ, not fresh ones. If serving scales features differently from training, the learned weights silently stop meaning anything.
DEMO 6.1 Train Pairwise Feature Weights Step-by-Step
Train a step · watch inversions drop to 0
Optimizer:
0.15
1.40
0.10
0.10
Pairwise Inversions 6 Goal: 0 misordered pairs
Top Ranked Doc Stuffed FAQ Updates as weights learn
Split Policy 75 / 20 / 5 Example split, grouped by qid

How LambdaMART works

Many production teams rerank with LambdaMART (see the note above). It works in three moves: it starts list-wise, goes pair-wise, and ends up point-wise.

  1. Swap and measure (list-wise). For one query, try swapping every pair of results and see how much a list metric like DCG changes. Swapping a great doc up past a bad one might improve DCG by 0.1.
  2. Turn swaps into "lambdas" (pair-wise). Add up those swap effects for each document. The result, its lambda, says how hard that doc should be pushed up or down. Each pair is weighted by how wrong the current model's order is, so pairs already ordered by a wide margin barely count.
  3. Fit trees to the lambdas (point-wise). Now each doc has a target number, so it's a normal regression problem. Gradient-boosted decision trees learn to predict the lambdas from features, and the lambdas are recomputed after every tree. Each new small tree fixes the errors of the ones before it, and the final score is the sum of all the trees.
  • A tree is just if-statements. "If title_bm25 > 2 and overview_bm25 > 2, score 12." Trees capture combinations ("title match and overview agrees") that a single linear weight can't, and they work on raw, unscaled features.
  • Why trees still win in production. The features that matter most are often tabular: popularity, PageRank, distance, price, plus lexical and embedding scores. Trees handle that mix well and are fast to run.
DEMO 6.2 One Tiny Tree From a LambdaMART Model
Move the features · watch which leaf fires
3.0
5.0
title_bm25 > 2 ?
yes
overview_bm25 > 2 ?
yes12title and overview agree
no7title only
no
overview_bm25 > 10 ?
yes8very strong overview
no1weak match → bottom
This Tree's Output12≈ the lambda it learned to predict
Real Model100s of treesFinal score = sum of all trees

The split values and scores here are just an example. A trained model picks its own splits from the data.

Putting it together: the automated LTR loop

Click models, LTR, and active learning are pieces of one loop that keeps running on its own: exploit, explore, gather, rinse, repeat.

StepWhat HappensPieces Used
1. ExploitTrain the LTR model on known features and the judgments you already have. Serve it.SDBN judgments (Demo 5.2), pairwise LTR (Demo 6.1)
2. ExploreGuess new "explore" features (like has_promotion) that cover blind spots in the training data. A Gaussian process with Expected Improvement can pick the most promising ones to show.Active learning (Demo 5.3 uses a simpler uncertainty bonus)
3. GatherMix explore results into live rankings and collect the new clicks.Signals logging (§3), click models (§5)
4. Rinse, repeatRebuild judgments from fresh sessions and retrain on a schedule (for example, daily). If the explore model now scores better than the exploit model, promote it to be the new exploit model.Offline evaluation, then A/B testing or interleaving
  • Why it needs a loop. A model trained only on past clicks can only learn from what it already showed. Exploring breaks that echo chamber, and retraining on fresh data lets the ranker follow trends and seasons.
  • Humans still steer. You pick the explore features, the click model, the model type, and the risk setting (θ) for how boldly to explore.
■ Takeaway · Next §7

Even with BM25, signals, and LTR, lexical search misses pages that use different words for the same problem (such as socket hang up vs. ECONNRESET). Next: dense vector search.

Next: §7 Embeddings
Part 3 Vectors Search by meaning instead of exact words.
§7 · Embeddings

Dense embeddings: text as points in space

A transformer bi-encoder maps text into a dense vector (768 or 1,024 floats) so similar meanings land close together. Unit-normalizing vectors at index time turns cosine similarity into a plain dot product. §9 covers how to search millions of them fast.

ArchitectureHow It ScoresWhere It Fits
Bi-EncoderEncodes query and doc separately, compares via dot productStage 1 retrieval over millions of docs (milliseconds with an ANN index, §9)
Cross-EncoderFeeds [CLS] query [SEP] doc [SEP] into full joint attentionStage 2 reranking of the top tens to hundreds of candidates (too slow to run on everything)
DEMO 7.1 Embeddings on a Sphere: Cosine Is an Angle
Drag the query arrow · watch the nearest pages change
Query:
meaning space · 3 dims (real models use 768+)
cosine to the query · ranked

Each dot is a page stored as a unit-length vector. Green = network errors, blue = accounts, amber = billing. Every vector has length 1, so cosine = dot product = how small the angle is.

  1. Start on "fix econnreset". The arrow points into the green cluster. All of the top 3 are network-error pages, and the billing pages sit far around the sphere.
  2. Click just "reset". The arrow lands between the green and blue clusters, so password pages and connection pages mix in the top 3. One word with two meanings gives one arrow that sits between them.
  3. Drag the arrow tip toward the amber dots. The ranking on the right reorders as the angle shrinks. Pages about 90° away score about 0.
  4. Drag empty space to spin the view. Dots that look close from one side can be far apart in depth. Flat pictures of embeddings can mislead for the same reason.

Where the vectors come from

  • One vector per token, not per sentence. The raw output is a list of token vectors. Search needs one vector per query or doc, so they get pooled.
  • Bi-encoder = two-tower model. Same thing, two names. It can be one shared encoder for both sides (like SBERT) or two separate towers. Asymmetric models also mark queries and documents differently (for example "query:" and "passage:" prefixes), because short queries and long documents look different. You can also train your own on search traffic: Reddit trained one on what users actually clicked. Off-the-shelf models only work well on the kind of matching they were trained for, so check before you use one.
Go deeper · 4 more notes
  • Subword tokens. A Transformer like BERT first splits text into WordPiece tokens. Common words stay whole, and rare ones break into pieces, so an unknown error code still gets a vector from its parts. Special tokens mark the start ([CLS]) and the breaks ([SEP]).
  • Attention gives context. Each token looks at every other token in the sentence and blends in what it learns. So reset in "connection reset" ends up with a different vector than reset in "reset my password".
  • Learned by filling in blanks. BERT trains itself with the Cloze test: hide about 15% of the tokens and predict them from the rest (masked language modeling). No labels needed, so it can read huge amounts of text.
  • SBERT: pooling + similarity tuning. Raw BERT vectors are poor at cosine search out of the box. Sentence-BERT averages the token vectors (mean pooling), then fine-tunes the model on sentence-pair data like NLI and STS-B, so that similar meanings really land close together. A name like roberta-base-nli-stsb-mean-tokens spells out the recipe. Mean pooling is the simple way to picture it, but pooling depends on the model, and some weight tokens differently using attention.
Mean Pooling (token vectors → one sentence vector)
$$\mathbf{v}_{\text{sentence}} = \frac{1}{n}\sum_{i=1}^{n} \mathbf{h}_i$$
h_i = the Transformer's output vector for token i n = number of tokens Then = unit-normalize so cosine = dot product
DEMO 7.2 One Vector per Chunk: How Averaging Waters Down Meaning
Change the chunk size · watch the on-topic part fade
Chunk size:
toy 2D meaning space · ◆ query "fix econnreset"
each chunk's cosine to the query

One release-notes page with 8 sentences. Only 2 are about connection resets. Thin arrows are sentences; thick arrows are what gets stored, the average of each chunk.

  1. Start on "Whole page". The page becomes one average vector. The ECONNRESET fix is in there, but six other topics pull the average away, so the page matches the query only weakly (cosine 0.46, versus 0.99 for the right chunk).
  2. Click "2 sentences". The chunk holding the two reset sentences points straight at the query. Smaller chunks keep sharp meaning.
  3. Click "1 sentence". Still a strong match, but each sentence is now alone: "Enable keepalive to avoid resets" no longer knows it's from the SDK v4 release notes. That lost context is why late chunking or late interaction is often better (see the chunking note below).
Go deeper · 1 more note
  • Contextual chunking and multivalued vector fields. Splitting a long page into isolated chunks strips away headings and parent metadata. Prepending section breadcrumbs, overlapping sliding token windows, and storing multiple chunk vectors in one parent document record keeps context intact. Avoid chunking if you can, because every split loses context. Best first: late interaction (one vector per token, far less dependent on chunk size, §10). Next: late chunking, also offered as "contextualized chunk embeddings", where the model reads the whole document first and then splits the token vectors into chunks, so each chunk still knows its context. Last: plain chunking.

Semantic autocomplete: "things, not strings"

A great first embedding project is autocomplete. Pull frequent noun and verb phrases out of your docs (dropping rare ones seen fewer than minimum_frequency times, which are mostly noise; start small and tune it on your data), embed each phrase once, and put them in an ANN index. As the user types, embed what they typed and return the nearest phrases. A classic suggester only finds phrases that start with the typed letters. The semantic one also finds phrases that mean the same thing. For example, typing dehyd can suggest dehydration, but also hydration pack.

DEMO 7.3 Prefix vs. Semantic Autocomplete
Pick what was typed · watch prefix vs. meaning
User typed:
"socket hang▌"
Prefix Suggester (strings) 1 found
Semantic Suggester (things) top 5
  1. Start on "socket hang". The prefix suggester finds the one phrase that starts with those letters. The semantic one also offers connection reset by peer and econnreset error, which are the same problem in other words.
  2. Click "conn dropped" or "slow api". No phrase starts with these letters, so the prefix list is empty. The semantic list still finds the right family: connection resets for the first, timeouts for the second.
  3. Click "too many". Both lists find too many requests. Only the semantic list adds rate limit 429 and retry-after header.

The vectors here are hand-made so you can see the idea. A real system embeds the typed text with the same model it used for the phrases (subword tokens let it handle half-typed words like idem), and checks quality against labeled data before shipping.

What embeddings are good at, and what they can't do

  • They rank; they don't match. Every document gets a similarity score, even a useless one. There's no natural line between "relevant" and "not", and finding a cutoff is a well-known weakness of embedding models. That's why filters and query understanding (§1, §4) still decide what is eligible.
  • Semantic drift. For example, a vector search for "The Hobbit" finds The Hobbit: An Unexpected Journey and other Middle-earth titles, which is great. But it also pulls in Harry Potter, which shares the "wizards and magic" neighborhood. Lexical search fails differently: it matched only the word the once the hobbit pages ran out. Hybrid search (§8) uses each to cover the other.
  • Numbers break embeddings. Models learn a meaning for each token, not a number line. The vector for 2 isn't reliably closer to 3 than to 10, so similarity between numbers is "spiky". Put prices, sizes, and versions in real fields and use range filters or a separate numeric feature.
  • Dimensions aren't human-readable. Toy examples (like the hand-made vectors behind Demo 7.3) give each axis one concept. Real 768-d embeddings spread each concept across many dimensions, which is how a few hundred numbers can hold millions of concepts.
  • Vectors can be added and averaged. Because meaning is position, the midpoint of two vectors lands near things that share both. Example: average a photo of a puppy with a photo of Darth Vader, and the nearest image is a puppy in a Darth Vader costume. Average a sporty car photo with the text "superhero" (in a shared image and text space like CLIP), and you find a superhero on a sporty car.
DEMO 7.4 Blend Two Concepts: Slide Between Two Vectors
Slide the mix · watch the nearest item change
Blend:
0.50

Embedding Space (toy 2D) ◆ = blended query
Nearest to the Query closest first
  1. Start at α = 0.50 on "puppy + Darth Vader". The query sits halfway, and the nearest image is the puppy in a Darth Vader costume, an item that matches neither word on its own.
  2. Drag α to 0 or 1. The query slides back to the plain puppy or the plain Darth Vader photo.
  3. Click "sporty car photo + "superhero"". Mixing an image vector with a text vector finds "superhero on a sporty car". This is how "find something like this photo, but with X" search works.

Real embeddings have hundreds of dimensions, and engines usually normalize the averaged vector. Two dimensions are enough to see why the midpoint works.

■ Takeaway · Next §8

Dense vectors handle synonyms and paraphrases, while BM25 still wins on exact error codes, SKUs, and rare terms. Most production systems run both, merge the lists (often with RRF), and then rerank the top results.

Next: §8 Hybrid search
§8 · Hybrid Search

Hybrid search: Reciprocal Rank Fusion vs. Relative Score Fusion

You cannot add raw BM25 scores (unbounded, 0 to ∞) to cosine similarity (bounded, -1 to 1). RRF ignores raw scores and sums reciprocal ranks. RSF min-max normalizes both lists to [0, 1] and takes a weighted average.

  • Reciprocal rank fusion (RRF). Uses only each page's place in each list. Agreement across lists beats a page that tops only one.
  • Relative score fusion (RSF). Rescales each list's scores to 0 to 1, then takes a weighted average. The catch: the last page in each list always scores 0, however close it was.
  • Match first, rerank second. The lexical match (the AND/OR lookup in the inverted index, §1) decides which pages qualify. BM25 then scores those pages, and a vector score or cross-encoder can reorder them. BM25 is the scoring step after matching, not the matching step itself.
Rank Fusion Formulas
$$\text{RRF}(d) = \sum_{m \in M} \frac{1}{k + r_m(d)} \qquad\qquad \text{RSF}(d) = w \cdot \hat{S}_{\text{BM25}}(d) + (1 - w) \cdot \hat{S}_{\text{vec}}(d)$$
BM25 contribution (green bar) Vector contribution (blue bar) k = 60 = standard RRF smoothing constant
DEMO 8.1 Side-by-Side: RRF vs. RSF on the Same Lists
Move k and w · watch RRF and RSF disagree
Scenario:
60
50% BM25
A. RRF (Rank-Only) Immune to score spikes
B. RSF (Min-Max Normalized Score) Preserves score gap
RRF #1 Winner Fixing ECONNRESET Ordinal ranks only
RSF #1 Winner Stuffed FAQ Normalized score sum
Do They Agree? Disagree Green=BM25 · Blue=Vec
  1. Start on "Outlier BM25 spike" (k = 60, w = 50%). RRF crowns "Fixing ECONNRESET" because #2 in BM25 plus #1 in Vector beats #1 plus #4. RSF crowns "Stuffed FAQ" because its raw BM25 spike (14.2 vs 5.4) dominates min-max scaling.
  2. Lower RSF weight w to 0.25. Now vector similarity drives RSF, and RRF and RSF agree on "Fixing ECONNRESET".
  3. Click "Consensus win" and drop RRF k to 1. At k = 1, first place counts far more than second place, so the RRF leader shifts to "Keep-Alive & Pools" (#1 in BM25, #4 in Vector). RSF still picks "Fixing ECONNRESET".
  4. Click "A page only one list finds" and set k back to 60. "Connection Resets" is #1 in the vector list, but BM25 never found it: the page says "connection reset", not "ECONNRESET". With one vote instead of two, RRF ranks it only #6.
  5. Drop k to 1. Its single first place now counts much more, and it climbs to #4 (tied with Changelog 2.4).
  6. Lower the RSF weight w to 0.10. RSF now trusts the vector scores, and Connection Resets takes #1 in RSF. Rescuing pages like this is why hybrid search exists; k and w decide how hard it tries.
■ Takeaway · Next §9

RRF ignores score-scale spikes; RSF keeps score margins when both engines are calibrated. Next: making vector search fast and small.

Next: §9 Fast, small vectors
§9 · Fast, Small Vectors

Making vector search fast and small

Storing 1 million 1536-dimensional FP32 vectors takes about 6 GB of RAM. Modern vector stacks combine quantization with two-stage rescoring (and sometimes Matryoshka Representation Learning, MRL) to cut memory by 20× to 100× with small recall loss.

Finding neighbors fast: HNSW and IVF

  • HNSW (Hierarchical Navigable Small World). A multi-layer proximity graph where upper layers hold long-range skip edges and the bottom layer holds dense local links, routing greedily in O(log N) hops.
  • IVF (Inverted File Index). Partitions vector space into Voronoi cells around k-means centroids (nlist). At query time you scan only the nearest nprobe cells.
  • Quantization plus over-request and rescore. Int8 scalar quantization cuts RAM by 75% with >92% recall; Product Quantization (PQ) compresses even further into sub-vector codebooks. Over-requesting top 50 quantized candidates and rescoring them with full FP32 vectors recovers most of the lost recall; a cross-encoder can then rerank the survivors for relevance. Some newer embedding models ship int8 vectors trained for it, which can be close to lossless compared with FP32.
DEMO 9.1 IVF Cluster Probing, Int8 Quantization & Cross-Encoder
Drag the query ◆ · watch which clusters get searched
Semantic Query:
HNSW Greedy Walk (from d8):
2 / 4 clusters
2D Embedding Space (IVF Cells) 0 hops · socket hang up on idle server
Retrieved Neighbors Cosine / Dot
Recall@3 vs. Exact 100% Of the exact top 3 · raise nprobe if low
Vector Memory 100%→25% FP32 vs. SQ8 footprint
Est. Query Latency 10 ms Toy numbers · real rerankers often add 100s of ms

Smaller vectors: Matryoshka and binary

  • Matryoshka Representation Learning (MRL). Trains embeddings so the most important information sits in the earliest dimensions. If the model was trained with MRL, you can slice a 1536d vector down to its first 256d prefix without retraining. It only works on MRL-trained models, and raw recall falls fast as you cut. In one test, halving the dimensions kept 70% recall, a quarter kept 48%, and an eighth kept 24%. Reranking the candidates with full vectors won most of it back. Most engines also fix the vector size in the schema, so slicing at query time usually isn't possible. In production, MRL is often more of a parlor trick: binary quantization plus reranking often gives better trade-offs.
  • Binary quantization (1-bit). Converts every float to 0 or 1 (32× smaller than FP32) and scores with hardware XOR + popcount (Hamming distance). The demo below scores a full-precision query against the 1-bit vectors (asymmetric scoring), which engines also offer.

The quantization ladder

Every option trades memory for accuracy. One trick makes them safe to use: keep the small, quantized vectors in RAM for the fast first pass, keep the full-size vectors on disk, and rerank the top candidates with the full vectors. You get close to the original results with far less memory.

MethodHow It WorksIn Practice
ScalarStore each number with fewer bits: float16, int8, all the way down to 2 bitsSimple, safe first step
Binary, naive1 bit per number: positive → 1, negative → 0Lowest quality of the binary options
Binary, tuned thresholdsLearn a better cutoff per dimension from your own dataKeeps much more detail at the same size
Binary, model-nativeThe model was trained to output bits directlyBest: a model trained for quantization beats quantizing afterwards
Product (PQ)Split the vector into M pieces; replace each piece with the ID of its nearest centroid (often a lookup table of 256 per piece; the demo below uses 4 to 64)Can go below 1 bit per dimension, but it's slower than binary. Prefer binary unless you need PQ's size
RotationalRotate the space first. Distances don't change, but one huge outlier value gets spread across all dimensionsLess error at the same bit budget, since one outlier no longer forces a huge range
MRLCut off the tail dimensions (only on MRL-trained models)More of a parlor trick than a production tool (see above)
  • "Recall" here means something else. In quantization and ANN benchmarks, recall = how many of the exact brute-force top results you still get. It does not say whether those results are relevant to the user. 95% ANN recall of a bad ranking is still a bad ranking. Relevance is measured with judgments (§11).
DEMO 9.2 Product Quantization: Pack a Vector into a Few IDs
Change the codebook size · watch bytes and error trade off
Codebook:
16-dim vector, split into 4 pieces · original vs. rebuilt from the codebook

Each piece of 4 numbers is replaced by the ID of its nearest entry in that piece's codebook. The codebooks are learned once, with k-means on 2,000 training vectors. Only the IDs are stored.

  1. Start with 16 entries. The vector is stored as 4 IDs of 4 bits each: 2 bytes instead of 64. The amber bars (rebuilt) follow the blue ones (original) roughly, piece by piece.
  2. Click "4 entries". Just 1 byte per vector, but with only 4 choices per piece, the rebuilt bars drift further from the truth.
  3. Click "64 entries". More choices fit better, at 3 bytes per vector. This is the knob: entries per codebook (and how many pieces) trade memory against accuracy.
  4. Click "Next vector" a few times. Some vectors fit the codebooks well, others don't. That's why search engines rerank the top hits with full vectors.
DEMO 9.3 Shrink the Vectors, Then Measure What You Lost
Pick a format · watch memory and recall trade off
Store as:
64 of 64 dims
one vector · original vs. what gets stored
recall@10 vs. memory · every format

A toy index of 2,000 vectors × 64 dims, 40 queries. "Recall@10" = how many of the exact FP32 top-10 results each format still finds.

RAM for 1M × 1,536-dim 5,859→1,465 MB FP32 → this format, in MB
Compression 4.0× smaller vs. full FP32
Recall@10 vs. Exact 97% → 100% First pass → after rerank
  1. Start on Int8. Each number is stored in 1 byte instead of 4, so memory drops 4×. The first pass still finds 97% of the exact top-10, and reranking with the full vectors finds all of them.
  2. Click "Binary (1-bit)". 32× smaller. The stored bars (amber) are now just + or −, and the first pass finds only 45%. Reranking the top 50 with full vectors brings it back to 93%: the fast-pass-then-rerank trick.
  3. Click "PQ". Half a bit per number: each chunk of 8 values is replaced by the ID of its nearest codebook entry. That's 64× smaller. The first pass finds 27%, and reranking brings it to 91%.
  4. Pick FP32 and drag MRL down to 16 dims. Only the first quarter of each vector is kept. Even without compression, the first pass drops to 57%, and reranking reaches 96%. Earlier dims hold more signal here because these toy vectors are built that way, like an MRL-trained model.
  5. Untick "Rerank". The recall tile now shows only the first pass (57% here); in the chart, the hollow dots are each format's first pass. The gap to the filled dots is why systems keep compressed vectors in RAM and full vectors on disk.

Why rotation helps: one outlier ruins the scale

A low-bit quantizer splits the range from −max to +max into a few steps. If one dimension is huge, the steps get huge too, and every normal value lands in the same one or two steps. Rotating the vector first (multiplying by a random orthogonal matrix) spreads that outlier across all dimensions. Lengths and dot products don't change, because rotation is exact. But the max shrinks, so the same bits describe every value more finely. That's the idea behind rotational quantization (TurboQuant).

DEMO 9.4 A Spike in 3D: Rotation Spreads the Length
Rotate the arrow · watch one big coordinate become three small ones
geometry · x and its rotation Rx
size of each coordinate · |Rx|

x = (1, 0, 0) puts all of its length in one coordinate. Any rotation of x is just another arrow of length 1, so dragging the tip is the same as picking a rotation.

Largest |coordinate|1.00→1.00spike → after rotating
Length1.000Always 1: rotation is exact
Best Possible in 3D0.577every coordinate = 1/√3
  1. Start on the spike. All the length sits on x₁: one coordinate is 1.00 and the other two are 0. A quantizer has to stretch its scale all the way to 1.00 to fit it.
  2. Click "Draw a fresh rotation" a few times. The arrow swings to a new direction and its length spreads over all three coordinates. The biggest one drops below 1, and the length stays 1.000.
  3. Drag the tip toward a corner of the cube. On the diagonal every coordinate is 0.58, the most even split 3D allows.
  4. Drag empty space to spin the view. The dashed lines show the three coordinates of the tip from any angle. The next demo does the same thing in 32 dimensions, where there is far more room to spread.
DEMO 9.5 Rotate, Then Quantize: Same Bits, Less Error
Change the bits · watch the error shrink after rotating
3 bits
before · one outlier (dim 5) sets the scale
after rotation · the outlier is spread out

Bars = values. Amber ticks = the level each value gets rounded to. Both charts use the same scale.

Largest |value|1.60→1.15before → after rotating
Vector Length1.730→1.730Unchanged: rotation is exact
Quantization Error (MSE)2.2e-2→6.7e-33.3× less error after rotating
  1. Start at 3 bits. On the left, the outlier at dimension 5 stretches the scale, so the small values all snap to the levels nearest zero (amber ticks). On the right, after rotating, no single value is that large, and the ticks track the bars closely.
  2. Read the tiles. The largest value shrinks, the length stays exactly the same, and the error drops several times over.
  3. Click "Draw a fresh rotation" a few times. Every random rotation helps, some more than others. Engines often use structured fast rotations instead of a full random matrix.
  4. Drag the bits up to 6. With more bits, both errors shrink by more than 50×, so what rotating saves in absolute terms becomes tiny. Rotation matters most when bits are scarce.
■ Takeaway · Next §10

Keep small quantized vectors in RAM, keep full vectors on disk, and rerank the top hits. That cuts memory by 20× to 100× with little recall loss. Next: going beyond one vector per document.

Next: §10 Beyond one vector
§10 · Beyond One Vector

Beyond one vector: ColBERT, SPLADE, and Wormhole Vectors

Compressing a 500-word document into one dense vector loses fine-grained token detail. Two architectures solve this from opposite directions without paying full Cross-Encoder latency.

  • Late interaction (ColBERT, ColPali). Stores one contextual vector per token at index time. At query time, each query token finds its single highest dot product across all document tokens (MaxSim), then sums those maximums. ColPali applies the same idea to PDF page image patches.
  • Sparse lexical expansion (SPLADE, Doc2Query). SPLADE uses a transformer to predict importance weights across the full vocabulary, expanding short text with synonyms like socket hang up → econnreset, keepalive, tcp so it runs directly inside a fast inverted index. Documents get expanded the same way at index time, so query and document terms can meet. Real SPLADE terms are the model's word pieces, so some expansions are word fragments rather than the clean words in the demo below. Doc2Query gets a similar effect differently: it generates likely queries and appends them to the document as text.
Go deeper · 3 more notes
  • System One (Decision Models) as rerankers. Compact decision models (such as pplx-decider-flash) score query-document relevance fast enough for production reranking, bridging classic cross-encoders and expensive frontier LLMs. Sizes run from about 1.7B up to roughly 21B to 31B for the top benchmark scores, and bigger usually does better. Reranking is only one job. Because they pick from a fixed list of answers, they also handle query classification and query understanding, routing (for example, which team gets this message), and fine-tuned domain classifiers. Decision models can replace a lot of what used to need a full LLM, often fast enough even for regular search. Expect hundreds of ms per rerank call, with big swings on hosted APIs.
  • Why "System One"? The name comes from the two modes of thinking: System 1 is fast and intuitive, System 2 is slow and deliberate. A decision model is built for System 1. It doesn't reason step by step; it picks one answer from a fixed list in a single step. Its confidence comes from the score the model gives each option's token, the same scores an LLM uses to choose its next word. The trade-off: speed and low cost, with a ceiling on accuracy for problems that need real thinking.
  • Watch the word "pairwise". In LTR (§6), pairwise means comparing doc A against doc B. In reranker APIs, "pairwise" often means scoring one (query, doc) pair per call, and "listwise" means sending all candidates together.
ColBERT MaxSim Scoring
$$\text{MaxSim}(Q, D) = \sum_{i=1}^{|Q|} \max_{j=1}^{|D|} \left(\mathbf{q}_i \cdot \mathbf{d}_j\right)$$
DEMO 10.1 ColBERT MaxSim Token Matrix
Switch documents · watch each token's best match
Candidate Doc:
Token-to-Token Dot Product Matrix Doc A: Fixing ECONNRESET in Node HTTP Pool
Total MaxSim Score 3.73 Sum of row maxima
Storage Cost 1 vec / token More RAM than single-vector
Latency vs Cross-Encoder ~100× faster Docs pre-encoded offline
DEMO 10.2 SPLADE: Learned Sparse Lexical Expansion
Pick a query · watch new terms get added
Query:
Expanded Sparse Term Weights Runs on an inverted index

Wormhole Vectors: jumping between vector spaces

  • Wormhole Vectors (traversing disjoint spaces). You cannot take a dot product between a dense text vector and a behavioral click vector. Wormhole vectors bridge them by retrieving top anchor docs in Space A, pooling their vectors in Space B, and querying Space B directly.
DEMO 10.3 Wormhole Vectors: Bridging Disjoint Spaces
Step through · watch the query jump spaces
Traversal step:
■ Takeaway · Next §11

One vector per token (ColBERT), learned sparse terms (SPLADE), and hops between spaces (Wormholes) each fill a gap that a single dense vector leaves. Next: measuring whether a change helped.

Next: §11 Measuring relevance
Part 4 Measuring Check whether a change made results better.
§11 · Evaluation

Measuring relevance: NDCG, recall, and MRR

Without offline metrics on a judgment list, tuning search is guesswork. NDCG@k rewards putting graded relevant docs (0 to 3) at the top, discounts lower ranks by log₂(i + 1), and divides by the ideal ordering so scores stay between 0 and 1.

  • G (Gain). Points for one result from its grade: 2^rel − 1. Grade 3 earns 7; grade 0 earns 0.
  • C (Cumulative). Add up the points of every result in the top k.
  • D (Discounted). Shrink each result by its rank: rank 1 counts 100%, rank 2 63%, rank 3 50%, rank 4 43%, rank 5 39%, and rank 10 only 29%.
  • N (Normalized). Divide by the score of the ideal order (IDCG) so queries stay comparable on [0, 1].
  • @k (Cutoff). Only the top k results count. Anything past rank k adds nothing.
Discounted Cumulative Gain & Normalization
$$\text{DCG}_k = \sum_{i=1}^{k} \frac{2^{\text{rel}_i} - 1}{\log_2(i + 1)} \qquad\qquad \text{NDCG}_k = \frac{\text{DCG}_k}{\text{IDCG}_k} \in [0, 1]$$
DEMO 11.1 Drag Results to Reorder: NDCG@k
Drag a row · watch NDCG fall
Presets: Gain:
@5
Cumulative DCG vs. IDCG NDCG@5 = 1.000 · ERR = 0.910
Ranked Results (Drag or ↑/↓) rel 0 to 3
NDCG@k 1.000 DCG / IDCG
ERR@k (Cascade) 0.910 Stop chance grows with grade
Actual DCG 10.82 Current ordering
Ideal IDCG 10.82 Best possible ordering
  1. Click "Best doc buried at #5". Moving the grade-3 page from rank #1 to rank #5 drops its weight from 100% to 39%, pulling NDCG@5 down from 1.000 to 0.748.
  2. Drag any row (or press ↑ / ↓). Watch the emerald DCG curve bow away from the amber IDCG ceiling whenever a lower-grade page sits above a better one.
  3. Toggle Gain from 2^rel - 1 to Linear (rel). Exponential gain punishes burying grade-3 docs much harder than linear gain; always verify which definition your eval library uses.
  • Pair NDCG@10 with recall@50 or @100. Recall tells you whether the right docs entered the candidate pool; NDCG@10 tells you whether the final order is good.
  • For agents and RAG, order matters less. When an LLM reads the top 10 to 20 results, it matters much less whether the best one is #1 or #8 (though LLMs still favor some positions in their input). Set-level recall (Recall@20) often tracks answer quality better than NDCG@10. NDCG still matters for ranked lists that people scan.
  • Graded vs. pass/fail labels. Simple good/not-good labels are faster to collect and more consistent between raters, and often enough for agent evals. Graded labels (0 to 3) still matter when you train a ranker like LTR, because it has to learn why one good result beats another.
  • MRR for one-right-answer search. When each question has one right answer, or labels mark about one relevant passage per query (as in MS MARCO, which reports MRR@10), score each query as 1 / rank of the first right answer and average over queries: rank 1 → 1.0, rank 2 → 0.5, rank 4 → 0.25. That's Mean Reciprocal Rank. RAG is different: it wants several useful passages, so recall-style metrics fit it better.
  • Unjudged docs count as irrelevant. So a new system that surfaces good but never-labeled pages gets penalized unfairly. Check how much of your top 10 is labeled, and check whether your library uses linear gain (rel) or exponential gain (2^rel − 1) before comparing numbers.
Go deeper · 5 more notes
  • The NDCG paradox. NDCG divides by the best order of the docs you judged. If every judged doc is only marginally relevant (say all grade 1), the best order is just as mediocre, so any order of them scores NDCG = 1.0 even though nothing is good. (If all are grade 0, NDCG is undefined; most libraries report 0.) Some teams divide by the best possible DCG (all top grades) instead.
  • IDCG uses all judged docs for the query. A relevant document you never retrieved still lowers your score.
  • Calibrate LLM-as-judge labels. Check agreement against a human-labeled sample (e.g., Krippendorff's alpha) before trusting NDCG deltas. Don't assume humans are the gold standard. Paid human raters are often noisy and rushed. LLM labels are consistent (though they can all share the same bias), and a judging rubric can be fixed and re-run like code. In published comparisons, LLM labels have matched real searchers' preferences better than paid crowd labels.
  • Expected Reciprocal Rank (ERR) and Session-Based Eval. ERR models a cascade user who scans down the list and stops at each result with a probability that grows with its grade. Session-based evaluation scores the whole multi-query journey rather than isolated queries.
  • BlitzRank tournaments and synthetic pairwise judgments. BlitzRank asks an LLM to rank small groups of documents, records every "A beat B" as an edge in a graph, and fills in pairs that never met by assuming wins carry over (A > B and B > C means A > C). LLMs aren't always consistent, so you get loops like A > B > C > A. BlitzRank treats each loop as a tie and groups those docs together (the paper calls them strongly connected components). It only sorts the top M you ask for. Below that the order isn't set, so don't read it as a ranking. The same pairwise pattern can bootstrap cold-start LTR datasets from clustered passages.
DEMO 11.2 Same Results, Four Metrics: Precision, Recall, MRR, NDCG
Click results to mark them good · watch each metric react differently
Presets:
5
ranked results · click to mark good / not good

In the presets, the collection has 5 good pages and at least one is never retrieved, so recall can't reach 100%. Mark extra rows good and they count as part of the collection.

metrics at k
  1. Start on "One great result at #1". MRR is a perfect 1.0: the first good result is at the top. Recall is low, because the other good pages are missing.
  2. Click "Lots of good results, messy order". Recall jumps (60% at k = 5, 80% at k = 10), which is what an agent reading the whole list cares about. MRR drops to 0.5 because the first good result is at #2. NDCG actually rises (0.34 → 0.51 at k = 5), because more good results now sit near the top even though #1 is a miss.
  3. Click "First good result at #6", then drag k from 5 to 6. At k = 5, every metric is 0: the good result is past the cutoff. At k = 6 they all wake up. Always check which k a number was measured at.
  4. Click any row to flip it between good and not good, and watch which metrics move. MRR only ever looks at the first good row.
■ Takeaway · Next §12

Without a judgment list and a metric, you cannot tell whether a change helped. Pick the metric that matches who reads the results: NDCG for people scanning a list, recall for an LLM reading all of it.

Next: §12 Answers and RAG
Part 5 AI Answers Turn search results into answers.
§12 · QA & RAG

From search results to answers: QA and grounded RAG

Search output sits on a spectrum, from only pointing at sources to writing something new. Each step to the right is more convenient for the user and less tied to the exact words of a source.

StepWhat the User GetsCovered On This Page
1. Search results"Ten blue links." Sources only.§1 to §11
2. Info boxesPre-vetted summary or answer for known entities and questionsNot covered
3. Extractive QAAn answer span copied word for word from a source, found in real timeDemo 12.1
4. Results summarizationSeveral results rewritten into one short summary, with citationsRAG (Demo 12.2)
5. Abstractive QAA new answer written from one or more results; may not match any source's wordingRAG (Demo 12.2)
6. New content generationNew prose, code, or images made on the fly from the queryNot covered

Steps 4 to 6 run on foundation models: huge models trained on vast amounts of web text and other data that can then be adapted to many tasks. Training is a kind of lossy compression: it squeezes human knowledge into the model's weights. Facts can be "decompressed" back out, but not perfectly. That is why models hallucinate, and why RAG hands them the real source text at answer time.

LeverWhat ChangesCost
PretrainingAll the weights, learned from scratch on a massive dataset (next-word prediction for generative LLMs; fill-in-the-blank masking for BERT-style encoders, as in §7)Weeks to months; millions of dollars or more
Fine-tuningSome or all weights, or new layers on top, trained on your domain data or instructions (like the QA reader in Demo 12.1)Much smaller training run
PromptingNo weights. You steer the output with instructions and context at inference time. RAG is prompting with retrieved passages.Per request, no training

Extractive QA, RAG grounding, and multimodal search

Modern search feeds answers directly to users or language models. In every case, generation quality is capped by retrieval recall: if the right passage never enters the context window, the model cannot cite it.

  • Extractive QA: retriever-reader. The search engine retrieves candidate passages (maximizing Recall@k). A fine-tuned reader model predicts two token distributions, P_start(i) and P_end(j), ranks spans by P_start(i) × P_end(j), and abstains when the [CLS] null score (P_start(CLS) × P_end(CLS)) beats the best span.
  • Grounded RAG and abstention. The LLM is constrained to answer strictly from retrieved passages with inline citations. If no chunk clears your similarity threshold τ, skip generation and return "not found" rather than hallucinating. A raw embedding cutoff is fragile. Embeddings rank; they don't match, and picking a cutoff is a well-known weakness of embedding models. Model scores also aren't true probabilities for your data. Use query understanding and filters to decide what's eligible, put thresholds on a reranker's score instead, or have an LLM check citations before answering.
Go deeper · 5 more notes
  • Multimodal retrieval. Models like CLIP project text and images into one shared embedding space, letting a text query retrieve diagrams, screenshots, or products using the same ANN index.
  • Golden sets and QA error taxonomy. Bootstrap a machine-labeled silver set, then audit with humans using four classes: 1 Correct, 0 Fixed, -1 Impossible/Abstain, and -2 Incorrect (a known-wrong span kept as a negative example).
  • Token offset alignment and SQuAD EM vs. F1. Long passages are sliced with sliding doc_stride windows while mapping character offsets to subword tokens. Extractive readers are scored with Exact Match (EM: exact equality after normalizing case, punctuation, and articles) and token-level F1 (partial overlap).
  • HyDE (Hypothetical Document Embeddings). For tough questions, ask an LLM to draft a hypothetical answer first and embed that draft so vector search matches document phrasing instead of short question phrasing.
  • Programmatic prompt optimization with DSPy. Instead of hand-tweaking fragile prompt strings, compile signatures and few-shot examples against an objective metric (Exact Match, F1, schema validity).
DEMO 12.1 Extractive QA: Start/End Span PMFs & [CLS] Abstention
Swap the question · watch the model abstain
Query:
0.12
DEMO 12.2 RAG Chunk Gate: Drag the τ Threshold Line
Drag the τ line · watch chunks pass or get blocked
0.65
Top-5 Retrieved Chunks vs. Cutoff τ

In practice, a fixed cutoff on raw embedding similarity is fragile (see the caveat above). The same gate works better on a reranker's score, after filters have already decided which chunks are eligible.

DEMO 12.3 One Similarity Cutoff Can't Fit Every Query
Drag the cutoff · watch it help one query and break the other
cosine of each retrieved chunk · ● relevant ● not relevant
  1. Start at τ = 0.70. For the specific query, it's perfect: every relevant chunk passes and no junk does. For the vague query, every relevant chunk is blocked, because its best matches only score in the 0.60s.
  2. Drag τ down to 0.58. The vague query finally gets its answers (plus one junk chunk of its own), but the specific query now lets in three junk chunks.
  3. Look for a τ that's right for both. There isn't one. Scores mean different things for different queries, which is why it's better to decide eligibility with filters and query understanding, or to threshold a reranker's score instead.
■ Takeaway · Next §13

An answer can only be as good as what retrieval found. If the right passage never comes back, the model cannot cite it. Next: search built for agents.

Next: §13 Agents and caching
§13 · Agents & Caching

Semantic caching and optimizing search for agents

Classic search was built for humans scanning 10 blue links in one shot. AI agents search differently: they decompose questions, run multiple tool calls, inspect gaps, and reformulate queries before answering.

DimensionSearch for HumansSearch for Agents
Latency budgetStrict (about 100 to 200 ms, single pass)Looser overall (seconds to minutes across many calls), but each search call must still be fast because it runs many times
Top priorityTop-heavy ranking quality (NDCG@10; the first few links must look right)Recall@20 + clean structured chunks + metadata
Query styleShort, ambiguous queries of 2 or 3 wordsIterative, self-rewriting, tool-filtered queries
Go deeper · 1 more note
  • Video RAG: MomentSearch architecture. Video retrieval indexes two things: overlapping transcript windows and video frames. Frames must be heavily thinned and deduplicated first, because video runs at 30 to 60 frames per second and most neighboring frames are nearly identical. A query runs three searches at once (BM25 on transcripts, vectors on transcripts, CLIP on frames). The two transcript lists are merged, and only then are speech and frames grouped into timestamped "moments" for reranking, an LLM check, and a timestamped answer. Plain transcripts say what was said and when, but not who. A multimodal LLM can watch the video and mark speaker changes.

A semantic cache stores past queries with their answers. When a new query comes in, embed it and look for a cached query that means almost the same thing: cosine similarity above a high cutoff, τ_cache. On a hit, return the stored answer and skip retrieval and the LLM. The risk is a false hit: a query that is close but not the same gets someone else's answer, the way a cache entry for "ipad" should not answer "ipad charger".

DEMO 13.1 Semantic Cache Hit/Miss & False-Positive Trap
Move τ_cache · watch hits turn into false hits
Incoming Query:
0.85
DEMO 13.2 Agentic Search: Multi-Hop Tool-Call Coordinator
Step the agent · watch it switch tools
Execution:

This demo splits BM25 and dense search into separate steps so you can see each one. In a real agent, it's better to give tools by data source ("search our wiki", "search the web") and handle BM25 + vectors inside each tool. Give an agent a "BM25 tool" and a "vector tool" over the same data, and it will probably just call both every time.

■ Complete Reference (§0 to §13)

This page covered inverted indexes, BM25, signals, knowledge graphs, personalization, LTR, click models, active learning, dense ANN, hybrid fusion, NDCG, QA, RAG, ColBERT, SPLADE, Matryoshka, Wormhole Vectors, semantic caching, and agentic search.

↑ Back to Top

Sources

The ideas are theirs; the demos, examples, and any mistakes are mine.