Lexical, semantic and hybrid retrieval
medium 6 minLexical retrieval and dense retrieval can disagree productively.
Video lesson · Chapter 1 of 4
One fault has two names
Theory
Read or listen first. About 2 min.
What it is
Lexical retrieval and dense retrieval can disagree productively. The former can preserve an exact error code; the latter can recover paraphrases. Fusion combines evidence from both rankings after each has searched the eligible corpus.
Why it exists
Track result identity across both lists. Measure performance separately on identifiers and paraphrases, then inspect whether fusion helps one population at the expense of the other. Rank fusion is a reasonable baseline when raw score scales differ.
Find both a fault code and its paraphrase
Inside this chapter
Chapter sources- Query Embedding
- Encode a query with the representation and preprocessing expected by the index. A change in language, casing policy or model-specific prefix can shift its neighbors. Test with known query–passage pairs and inspect nearest results before changing the generator or adding more retrieved text.
The query must go through the same pipeline the encoder expects: the same model version, any query-side instruction or prefix, and the same text clean-up. Small mismatches do not raise errors; they just move the query vector a little, and neighbours shift. Keep a handful of known question and answer pairs as a smoke test and check their ranks after any change.
Example. For a model with query and passage prefixes, encode a known question both ways. Check how the rank of its answer passage changes.
A query on its way to the index - 1Raw questionhow do I reset my PIN
- 2Same clean-up as docscasing, whitespace, codes kept
- 3Add query prefix
query: how do I reset my PIN - 4Same encoder versionone vector, same space
- 5Nearest neighboursanswer passage at rank 1
Skip the prefix or change the model and the answer passage quietly slides down the list.
- Similarity Search Mechanics
- Similarity search scores or ranks candidates using the index metric. Some APIs return distances where smaller is closer; others return similarities where larger is better. Verify the contract with a point identical to the query and an orthogonal point before implementing a score threshold.
Different engines report different things: cosine similarity, cosine distance (one minus similarity), squared Euclidean distance or raw inner product. A threshold written for one is inverted for another. Querying with a vector already in the index tells you instantly which direction is better, and an orthogonal vector tells you what "unrelated" looks like.
Example. Search an index with one of its stored vectors. Determine whether the expected best result has the smallest distance or the largest score.
Learn the score contract before setting a threshold
- Top-K Retrieval
- Top-k caps how many candidates survive retrieval. A larger k may recover additional evidence but increases reranking cost and can exhaust context. Measure recall at several values and distinguish the number retrieved from the smaller number of passages ultimately sent to the generator.
There are really two k values: how many candidates the first stage retrieves, and how many passages reach the generator. Retrieving more raises recall but costs rerank time and offers more chances for distractors. Plot recall against k on a labelled set, choose the retrieval k where the curve flattens, then choose the final k from the token budget.
Example. Compare recall at k = 3 and k = 10, then count how many of the ten candidates can actually fit in the final prompt.
Recall rises with k, but the prompt is fixed
k Recall@k Rerank cost Fit in prompt 3 0.60 3 pairs 3 of 3 10 0.85 10 pairs 4 of 10 50 0.95 50 pairs 4 of 50 Illustrative numbers. Retrieve wide for recall, rerank, then send only what fits. - Result Ranking & Scoring
- Scores from different retrievers can use incompatible scales. Normalize with a justified method or combine ranks, then measure relevance on labeled queries. Keep each original score and rank in traces. Otherwise a ranking regression can be impossible to attribute to the lexical or dense stage.
Lexical scores are unbounded and depend on document length and term rarity; cosines sit roughly between minus one and one and cluster differently per encoder. Adding them directly lets one scale dominate. Either normalise each list with a method you have tested (for example min-max per query) or combine ranks, and log every original score and rank so you can tell which side caused a change.
Example. One system scores a document 12 and another scores it 0.8. Inspect the ranks within each list before treating the numbers as comparable.
Raw scores are not comparable; ranks are
Doc Lexical score Lexical rank Cosine Dense rank P4 12.0 1 0.78 3 P9 6.5 4 0.84 1 P5 absent absent 0.80 2 Illustrative. A BM25 score of 12 and a cosine of 0.84 live on unrelated scales. - BM25 lexical scoring
- The standard lexical ranking function. A document scores higher when it contains rare query terms, contains them more often (with diminishing returns), and is not unusually long.
Three ideas are packed into the formula. IDF rewards rare terms. The fraction saturates, so the tenth occurrence of a word adds far less than the first. The length term penalises long documents that match only because they contain lots of words. BM25 knows nothing about synonyms, which is exactly why it complements dense retrieval rather than replacing it.
Example. In a support index, "E17" appears in two documents out of ten thousand, so it carries a large weight. "Card" appears in thousands and adds little.
BM25 for query terms q₁ … qₙ
f is the term count in D, |D| the document length, avgdl the average length. k₁ controls saturation, b controls length normalisation; common defaults are around 1.2 and 0.75.
How it works
Step through the idea, or press Play.
Term matches. P4 rank 1 · P9 rank 4
Understand it
Worked example
Find both a fault code and its paraphrase
- 1
P4 rank 1 · P9 rank 4
The rare code E17 is a strong lexical signal. This index supplies ranked IDs with its own score scale.
- 2
P9 rank 1 · P4 rank 3
“Charged twice” retrieves the useful P9 even without the error code. The dense score scale need not match the lexical scale.
- 3
P4 narrowly outranks P9
For equal weights and fusion constant 60, P4 receives 1/61 + 1/63. P9 receives 1/64 + 1/61. Keep upstream ranks to explain the difference.
Reciprocal rank fusion
Follow the handoffs
Reciprocal rank fusion with k = 60
| Doc | Lexical rank | Dense rank | 1/(60+r) terms | RRF |
|---|---|---|---|---|
| P4 | 1 | 3 | 1/61 + 1/63 | 0.03227 |
| P9 | 4 | 1 | 1/64 + 1/61 | 0.03202 |
Two retrievers feed one fused list
Summary
The whole topic in one minute.
Raw scores need not have comparable meanings. Rank fusion combines ordering without assuming identical score units.
Track result identity across both lists. Measure performance separately on identifiers and paraphrases, then inspect whether fusion helps one population at the expense of the other. Rank fusion is a reasonable baseline when raw score scales differ.