14.1 From Lexical to Semantic Search
A support desk has two requests. One customer writes flat tire, while the repair manual says patch punctured wheels. Another sends only the activation code XJ-992-B. The repair search needs to bridge a vocabulary gap. The code search needs to preserve every character. In a retrieval-augmented generation (RAG) system, the passages that survive this first search determine which evidence the generator can cite.
1. The Limits of Keyword Search
A. The Synonym Problem (Vocabulary Mismatch)
A lexical index maps terms to the documents that contain them. If the analyzer leaves flat tire and punctured wheels as four different terms, their BM25 overlap is zero. A synonym dictionary could bridge the gap. It needs to cover the vocabulary your readers actually use.
B. Polysemy (Context Blindness)
A query for bank alone leaves a lexical retriever with both financial and riverbank documents. Adding flood can change a term-based ranking as well as a vector ranking. An ambiguous query can remain ambiguous in either representation.
C. Cross-Lingual Limitations
A Korean support request can refer to an English manual with no shared words. Translation or a multilingual encoder supplies a bridge. A part number can already match across both languages, provided the analyzer preserves it as a searchable unit.
D. The Solution: Vector Embeddings
A dense retriever learns to map a query and a passage to vectors. Karpukhin et al. trained separate query and passage encoders to give answer-bearing passages a higher dot product than competing passages [3]. Whether a new pair of expressions lands close together is a question for an evaluation set.
2. Interactive Concept: Lexical vs. Semantic Search
Compare four support titles with two scoring rules. BM25 uses the title terms. Cosine similarity uses a small vector whose coordinates count words in three topic dictionaries, in the order wheel, activation and learning. Open the dictionary in the exercise to see every word. A learned retriever would estimate its representation from data. Here the word groups are chosen by hand so you can compute every score.
Which title should win for activation XJ-992-B? A and B mention activation, but only B contains the product code. Check both scores below. Each example link reopens that query, including in the other edition. Text you type stays in this tab.
Words counted in each topic vector
- wheel · flat, tire, punctured, wheels
- activation · activation
- learning · ai, book, learning, textbook
Query vector (wheel, activation, learning) [2, 0, 0]
| Title | Vector | BM25 | Cosine |
|---|---|---|---|
| A · Device activation guide | [0, 1, 0] | 0.000 | 0.000 |
| B · Device activation XJ-992-B | [0, 1, 0] | 0.000 | 0.000 |
| C · Patch punctured wheels | [2, 0, 0] | 0.000 | 1.000 |
| D · Machine learning textbook | [0, 0, 2] | 0.000 | 0.000 |
Highest BM25 · no matching term
Highest cosine · C
Query vector (wheel, activation, learning) [0, 0, 0]
| Title | Vector | BM25 | Cosine |
|---|---|---|---|
| A · Device activation guide | [0, 1, 0] | 0.000 | — |
| B · Device activation XJ-992-B | [0, 1, 0] | 1.204 | — |
| C · Patch punctured wheels | [2, 0, 0] | 0.000 | — |
| D · Machine learning textbook | [0, 0, 2] | 0.000 | — |
Highest BM25 · B
Highest cosine · undefined for a zero query vector
Query vector (wheel, activation, learning) [0, 1, 0]
| Title | Vector | BM25 | Cosine |
|---|---|---|---|
| A · Device activation guide | [0, 1, 0] | 0.693 | 1.000 |
| B · Device activation XJ-992-B | [0, 1, 0] | 1.897 | 1.000 |
| C · Patch punctured wheels | [2, 0, 0] | 0.000 | 0.000 |
| D · Machine learning textbook | [0, 0, 2] | 0.000 | 0.000 |
Highest BM25 · B
Highest cosine · A, B
Query vector (wheel, activation, learning) [0, 0, 2]
| Title | Vector | BM25 | Cosine |
|---|---|---|---|
| A · Device activation guide | [0, 1, 0] | 0.000 | 0.000 |
| B · Device activation XJ-992-B | [0, 1, 0] | 0.000 | 0.000 |
| C · Patch punctured wheels | [2, 0, 0] | 0.000 | 0.000 |
| D · Machine learning textbook | [0, 0, 2] | 0.000 | 1.000 |
Highest BM25 · no matching term
Highest cosine · D
The Keyword Stronghold: Precision on Specifics
In the product-code example, the rare code earns a larger BM25 contribution than the shared word activation. For a term found in of titles, the exercise uses [4]. BM25 uses for term-frequency saturation and for length normalization. Each distinct query term contributes once. All titles are three terms long and no title repeats a term, so the usual factor equals 1 for each match. Here is title length, is mean title length and is the term’s frequency in that title.
A scores and B adds to reach 1.897 (rounded). Their topic vectors are identical, so both cosine scores equal 1. With the code alone, B still matches lexically. The dictionary has no entry for the code, so the query vector has zero length and cosine is undefined. A dash in the table marks that case. Query and title tokens are converted to lowercase, keep internal hyphens, and use no stemming or morphological analysis.
Follow the flat tire example to see the other failure. No title contains either term, so all four BM25 scores are zero. The dictionary gives the query and title C, Patch punctured wheels, the same direction, for a cosine of 1. Type tire activation and C shares just one of the two query coordinates. Its cosine drops to .
Reproduce the scores in Python. The example uses the standard library and the four-title corpus statistics above.
from math import hypot, isclose, log1p
# Four three-token titles. Each matched term occurs once, so its BM25
# contribution here is its inverse document frequency.
def idf(df):
return log1p((4 - df + 0.5) / (df + 0.5))
def cosine(q, d):
norm = hypot(*q) * hypot(*d)
return sum(a * b for a, b in zip(q, d)) / norm if norm else None
general = idf(2)
specific = idf(2) + idf(1)
print(round(general, 3), round(specific, 3)) # 0.693 1.897
assert isclose(cosine([1, 1, 0], [2, 0, 0]), 2**-0.5)
assert cosine([0, 0, 0], [0, 1, 0]) is None
A held-out set for a support search should include paraphrases and exact codes with labeled answer-bearing passages. Count how often each retriever includes that passage within the same candidate budget. Section 14.3 combines the two ranked lists and shows why a passage discarded by both retrievers cannot be rescued by a reranker.
Can a Korean question find the right English manual?
Consider four new English support passages written for this experiment. A tells owners of the fictional XJ-992-B to send the device in for a battery replacement. B tells owners of the XJ-992-D to open the cover themselves. C explains how to patch a bicycle inner tube. D explains how to download a receipt. Which passage should a search return for a Korean customer asking if they can replace the battery? The model number determines which instructions apply.
We wrote four requests in English and Korean and labeled the applicable passage before running either search. The table shows the Korean queries, glossed in English. BM25 scores the passage text with the settings above and keeps hyphenated codes intact. It uses no translation, stemming, stopword removal or Korean morphological analysis. “No match” means every passage scored zero.
| Korean request (English gloss) | Relevant passage | BM25 first | Multilingual E5 first (cosine) |
|---|---|---|---|
| My bicycle tire keeps losing air. How do I fix it? | C | No match | C (0.773619) |
| I want another copy of the receipt for a purchase last month. | D | No match | A (0.776618) |
| Can I replace the battery in my XJ-992-B myself? | A | A | B (0.862082) |
| Can I replace the battery in my XJ-992-Q myself? | No passage | No match | B (0.859964) |
E5 found the tire repair across languages. For the receipt it put the battery manual just ahead of D (0.776510). The English receipt request retrieved D first (0.850531). With only four passages, even a top result can be a near tie. These paired examples show failure modes and give no estimate of how often customers encounter them.
For a product-specific request, try requiring an exact catalog code before ranking. This leaves only A for XJ-992-B and an empty set for XJ-992-Q. A support tool can ask the customer to verify the unknown code before giving instructions. A cosine cutoff alone cannot both keep the correct Korean tire result and reject the higher-scoring result for the missing model.
Reproduce the CPU run (2026-11-25). The script pins the MIT-licensed intfloat/multilingual-e5-small checkpoint. It adds query: and passage: in both languages, averages the non-padding token vectors, L2-normalizes each 384-dimensional vector and ranks all four passages by dot product before rounding [5]. Download the Python script and setup commands.
3. Advanced Chunking Strategies
A. Naive (Fixed-Size) Chunking
Suppose a manual puts XJ-992-B at the end of one paragraph and its reset procedure in the next. A fixed 256-token boundary can separate the identifier from the instructions. An overlap of 20 tokens helps only if it preserves enough of the connection. Inspect the actual returned span.
B. Hierarchical Chunking
One option is to index section summaries, then search passages within a selected section. This saves work once the right section is selected. A missing detail in the summary can send the query to the wrong section before any passage is scored.
C. Parent-Child (Small-to-Large) Chunking
Index a short passage that names the code, then expand its source ID to the surrounding section before generating an answer. Retain the matched span, source revision and access rules when expanding. Evaluate passage recall and the fraction of final contexts that contain the complete procedure. The second measure catches a correct hit followed by a truncated answer.
4. The Mathematics of Semantic Space (InfoNCE and Matryoshka)
Contrastive Learning and InfoNCE Loss
For a batch of query–passage pairs, suppose passage is labeled relevant to query . An in-batch contrastive loss compares it against all in the batch. With similarity function and positive temperature , one common form is
The softmax normalizes the scores for one query across the batch. If another passage in the batch also answers that query, treating it as a negative sends the wrong training signal. Check labels and near duplicates when constructing the batch. Dense Passage Retrieval uses in-batch negatives and also studies harder negatives drawn from a lexical retriever [3].
Matryoshka Representation Learning (MRL)
Matryoshka training puts an objective on several prefixes of a representation [1]. Keeping 128 of 768 coordinates reduces raw coordinate storage sixfold at fixed precision. An arbitrary embedding can lose its most useful coordinates when truncated. For a model trained for nested dimensions, measure quality at each supported prefix and apply the required normalization after truncation.
October Update: Embeddings Across Modalities
As of 2026-11-25, Google’s October 6 release describes EmbeddingGemma 2 embeddings for text, images, audio and video, with supported dimensions down to 128 from 768 [2]. For example, a support query can retrieve a repair video. To cite the result, retain the video revision and time span along with the vector. Changing the encoder, dimension, preprocessing or normalization requires a compatible index and a fresh evaluation on each modality you serve.
Quizzes
Quiz 1: Why do two titles tie on cosine for “activation XJ-992-B” while B wins on BM25?
The dictionary assigns one activation coordinate to each title and none to the code. BM25 counts the rare code in B as well as the shared term.
Quiz 2: What does a dash in the cosine column mean for the code-only query?
The query has no recognized topic word. Its norm is zero, so there is no cosine score to rank. The code can still match a lexical index.
Quiz 3: If a retrieved chunk contains the part number but no reset instruction, what would you test?
Follow its source ID to the parent section and check whether the final context includes the full authorized procedure. A correct document ID alone cannot verify that the generator received the useful span.
Quiz 4: Would truncating any 768-dimensional embedding to 128 preserve its ranking?
There is no such guarantee. Nested training gives the prefix its own learning objective. Evaluate rankings at the chosen dimension with the model’s required normalization.
Quiz 5: What happens if the support tool accepts every top cosine of 0.80 or higher?
It rejects the correct Korean tire result (0.773619) and accepts a battery procedure for an absent model (0.859964). An exact catalog check can detect the missing model independently of the similarity score.
References
- Kusupati, A., et al. (2022). Matryoshka Representation Learning. Paper.
- Google (2026-10-06). EmbeddingGemma 2 release.
- Karpukhin, V., et al. (2020). Dense Passage Retrieval for Open-Domain Question Answering. EMNLP paper.
- Apache Lucene. BM25Similarity, inverse document frequency and parameter definitions.
- Wang, L., et al. Multilingual E5 Small model card, checkpoint and retrieval instructions.