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).
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
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.
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.
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).
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.
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.
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%.
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.
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).
Go deeper · 3 more notes
- Stemming vs. lemmatization. Stemming chops suffixes with simple rules (
retriesbecomesretry,runningbecomesrun; exact output depends on the stemmer). Lemmatization uses a dictionary sobettermaps togood, 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
theorinshrinks 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 containstheonce 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).
| 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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₁.
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.
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 Rule | What Qualifies |
|---|---|
Exact phrase | Only 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 |
- Start on "Any word (OR)" with Filter checked. Seven pages match at least one word. The filter
category = docsremoves the changelog (d4) without affecting any score, so six survive. - Switch to "All words (AND)". Only pages containing both
econnresetandretrysurvive. Precision goes up, recall drops. - Switch to "Exact phrase". Zero pages contain the literal two-word phrase
"econnreset retry", even thoughd1solves the exact problem. That is why phrase queries belong in a boost clause rather than a hard requirement. - 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. At75%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 itminimum_should_match. It takes a count (2) or a percent (75%). - Step functions. One rule can change with query length.
mm=2<-30% 5<3means: 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.
Matching gives you the eligible set. The first textbook formula people try for ranking it, TF-IDF, breaks on two common docs patterns.
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× relevant | Saturation controlled by k₁ |
| Long docs win by default: more words, more matches | Length normalization controlled by b |
- 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 ofeconnresetcount 14 times, even though it never saysretry. BM25 (right) caps the repeats, so "Fixing ECONNRESET", which has both words, stays #1. - 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.
- 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.
- 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
ECONNRESET5 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 crossk₁ + 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.
- 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.
- 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.
- 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%.
- 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.
- 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.5makes 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; atiesetting blends in the others). The demo below simply adds the fields, like Elasticsearch'smost_fields. - Phrase boosts (
pf,pf2,pf3).pfboosts the full phrase,pf2every two-word pair, andpf3every three-word run. They only add score. They never remove a page. - The
explaintree. For each matched word, the engine prints the boost, the IDF (withnandN), and the TF part (withfreq,k1,b,dl,avgdl), then adds them up. Reading it is the first step in any relevance bug hunt.
- Start on "connection reset" with "Body only". Pages are ranked by body BM25 alone. Click a few rows and read their explain trees.
- Click "qf title^3 body^1".
d2("HTTP Keep-Alive & Connection Pools") hasconnectionin its title, so its title score is tripled and it moves up. - Click "+ pf2^2". Pages where
connectionandresetsit side by side get a phrase bonus. The explain tree shows it as its own line. - 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) andd6(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.
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.
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.
- 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.
- 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.
- Click "Trending". With no weight on distance, the pro trade-deadline recap (5,200 clicks, 2 days old) takes #1.
- 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.
| Model | Kind of Relevance | What It Learns | Where It Breaks |
|---|---|---|---|
Signals boosting (§3) | Popularized | Which docs people pick for this exact query | Queries with few or no clicks, and brand-new docs |
Collaborative filtering (§3) | Personalized | What this user tends to like, from their past actions | New users and new items (cold start) |
Learning to rank (§6) | Generalized | Which features make any doc relevant (title match, recency, …) | Needs good features and training labels |
Knowledge graph learning (§4) | Semantic | Related terms, synonyms, and misspellings, mined from query logs | A 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.
- 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.
- Drag w down to 3. The additive bonus shrinks and "Fixing ECONNRESET" wins again. With "+", the result depends on picking just the right weight.
- 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.
- 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).
- 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.
- Raise w to 1. Times: the Troubleshooting Guide now wins both searches, so the two searches still agree. Plus: they still disagree.
- 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
resultsevent 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).
Weights: click = 1, copy_code = 10, helpful = 25, not_helpful = −20.
- 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. - Turn on "One vote per user". The bot now counts once.
d1(the real fix) takes #1 with +26. - Turn on "Normalize query text". Searches typed as
ECONNRESET," EconnReset ", andEconnresetnow count too.d1climbs to +48. - 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.
- 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.
- 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.
- 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.
- Pick "New User". There is no history, so the ranking falls back to plain BM25.
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.
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 upandECONNRESET), misspellings, and multi-word phrases automatically. - Two-level sense disambiguation. An ambiguous word like
drivercannot be expanded blindly. A two-level SKG traversal first identifies the category (databasesvs.golforrideshare) and then expands terms only inside that subgraph. - Semantic functions. Trigger words like
top,near, orunder $50do not belong in the keyword query. The transform step converts them into rating boosts, geospatialgeofiltclauses, 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_aclass hierarchies) instead of dumping everything into one synonym file.
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.
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 (advilforpain). Near0: no link, which is where stop words liketheland, 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.
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.
- 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.
- 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.
- Click "invoice". It shows up far less than chance in econnreset posts. It belongs to a different topic, so the score goes negative.
- 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.
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.
- 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.
- 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.
- 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.
- 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.
- Start (0.55 / 0.65, scaled by length). 9 typos get fixed and nothing goes wrong. The real word
pullis a typo candidate, but it is left alone. Bothidempotenttypos are missed, becauseidempotent(210 users) is below the correction cutoff. - Lower the correction cutoff to 0.60.
idempotentbecomes a correction, and both of its typos get fixed: 11 right. - 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 wordpullbecomespool. That is why short words get only 1 edit. - 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 typotimoutbecomes a "correction", sotiemoutgets mapped to another typo.
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.
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.
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.
- 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.
- 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.
- 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.
Breaking presentation bias with active learning
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.
Position-corrected clicks become the judgments a ranker trains on. Next: learning to rank from them.
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 Paradigm | What the Model Predicts | Trade-Off |
|---|---|---|
Pointwise | Single relevance score per doc | Simple, ignores relative order between docs |
Pairwise | Whether doc A beats doc B: w · (x_A − x_B) | Strong default; directly models ranking swaps |
Listwise | Whole 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?"
- 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.
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.
- 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.
- 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.
- 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.
title_bm25 > 2 ?overview_bm25 > 2 ?
overview_bm25 > 10 ?
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.
| Step | What Happens | Pieces Used |
|---|---|---|
1. Exploit | Train 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. Explore | Guess 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. Gather | Mix explore results into live rankings and collect the new clicks. | Signals logging (§3), click models (§5) |
4. Rinse, repeat | Rebuild 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.
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.
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.
| Architecture | How It Scores | Where It Fits |
|---|---|---|
Bi-Encoder | Encodes query and doc separately, compares via dot product | Stage 1 retrieval over millions of docs (milliseconds with an ANN index, §9) |
Cross-Encoder | Feeds [CLS] query [SEP] doc [SEP] into full joint attention | Stage 2 reranking of the top tens to hundreds of candidates (too slow to run on everything) |
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.
- 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.
- 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.
- 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.
- 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
resetin "connection reset" ends up with a different vector thanresetin "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-tokensspells 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.
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.
- 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).
- Click "2 sentences". The chunk holding the two reset sentences points straight at the query. Smaller chunks keep sharp meaning.
- 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.
- Start on "socket hang". The prefix suggester finds the one phrase that starts with those letters. The semantic one also offers
connection reset by peerandeconnreset error, which are the same problem in other words. - 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.
- Click "too many". Both lists find
too many requests. Only the semantic list addsrate limit 429andretry-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 wordtheonce 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
2isn't reliably closer to3than to10, 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.
- 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.
- Drag α to 0 or 1. The query slides back to the plain puppy or the plain Darth Vader photo.
- 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.
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.
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.
- 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.
- Lower RSF weight w to 0.25. Now vector similarity drives RSF, and RRF and RSF agree on "Fixing ECONNRESET".
- 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".
- 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.
- Drop k to 1. Its single first place now counts much more, and it climbs to #4 (tied with Changelog 2.4).
- 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.
RRF ignores score-scale spikes; RSF keeps score margins when both engines are calibrated. Next: making vector search fast and small.
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 nearestnprobecells. - 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.
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
0or1(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.
| Method | How It Works | In Practice |
|---|---|---|
Scalar | Store each number with fewer bits: float16, int8, all the way down to 2 bits | Simple, safe first step |
Binary, naive | 1 bit per number: positive → 1, negative → 0 | Lowest quality of the binary options |
Binary, tuned thresholds | Learn a better cutoff per dimension from your own data | Keeps much more detail at the same size |
Binary, model-native | The model was trained to output bits directly | Best: 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 |
Rotational | Rotate the space first. Distances don't change, but one huge outlier value gets spread across all dimensions | Less error at the same bit budget, since one outlier no longer forces a huge range |
MRL | Cut 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).
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.
- 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.
- Click "4 entries". Just 1 byte per vector, but with only 4 choices per piece, the rebuilt bars drift further from the truth.
- 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.
- 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.
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.
- 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.
- 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.
- 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%.
- 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.
- 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).
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.
- 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.
- 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.
- Drag the tip toward a corner of the cube. On the diagonal every coordinate is 0.58, the most even split 3D allows.
- 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.
Bars = values. Amber ticks = the level each value gets rounded to. Both charts use the same scale.
- 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.
- Read the tiles. The largest value shrinks, the length stays exactly the same, and the error drops several times over.
- 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.
- 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.
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.
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, tcpso 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.
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.
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.
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
kresults count. Anything past rankkadds nothing.
- 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.
- 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.
- Toggle Gain from
2^rel - 1toLinear (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 answerand 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.
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.
- 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.
- 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.
- 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.
- 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.
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.
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.
| Step | What the User Gets | Covered On This Page |
|---|---|---|
1. Search results | "Ten blue links." Sources only. | §1 to §11 |
2. Info boxes | Pre-vetted summary or answer for known entities and questions | Not covered |
3. Extractive QA | An answer span copied word for word from a source, found in real time | Demo 12.1 |
4. Results summarization | Several results rewritten into one short summary, with citations | RAG (Demo 12.2) |
5. Abstractive QA | A new answer written from one or more results; may not match any source's wording | RAG (Demo 12.2) |
6. New content generation | New prose, code, or images made on the fly from the query | Not 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.
| Lever | What Changes | Cost |
|---|---|---|
Pretraining | All 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-tuning | Some 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 |
Prompting | No 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)andP_end(j), ranks spans byP_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:
1Correct,0Fixed,-1Impossible/Abstain, and-2Incorrect (a known-wrong span kept as a negative example). - Token offset alignment and SQuAD EM vs. F1. Long passages are sliced with sliding
doc_stridewindows 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).
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.
- 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.
- 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.
- 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.
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.
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.
| Dimension | Search for Humans | Search for Agents |
|---|---|---|
| Latency budget | Strict (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 priority | Top-heavy ranking quality (NDCG@10; the first few links must look right) | Recall@20 + clean structured chunks + metadata |
| Query style | Short, ambiguous queries of 2 or 3 words | Iterative, 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".
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.
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.
Sources
The ideas are theirs; the demos, examples, and any mistakes are mine.
- AI-Powered Search, by Trey Grainger, Doug Turnbull, and Max Irwin (Manning, 2025).
- AI-Powered Search: Modern Retrieval for Humans & Agents, a live course on Maven taught by Trey Grainger and Doug Turnbull.