Embeddings & Vector Search
Contrastive embeddings, HNSW, hybrid search and retrieval metrics.
Part 4 is about giving a model knowledge and behavior it did not get from pretraining. The first tool is search by meaning. An embedding turns a piece of text into a point in space, so that finding relevant text becomes finding nearby points. Everything in retrieval-augmented generation rests on how well that works.
This chapter measures it. I trained an embedding model from scratch and tested it, alongside classic keyword search, on a public question-answering dataset: 20,963 Wikipedia paragraphs, 87,599 questions for training, and 2,000 held-out questions about articles the model never saw. Several results are not what the usual advice predicts.
14.1What an embedding is
One vector per text, with meaning as position and similarity as distance.
Section 2.3 introduced embeddings for single tokens. A text embedding does the same for a whole sentence or passage: a model reads the text and outputs one vector, typically a few hundred to a few thousand numbers. Texts with related meanings get vectors that point in similar directions. “How do I reset my password?” and “I forgot my login details” share almost no words and land close together; “What is your refund policy?” lands far from both.
The model that does this is separate from your chat model and much smaller. Its vectors turn search by meaning into a geometry problem: embed every document once, embed the query when it arrives, and return the documents whose vectors are nearest. The same trick powers deduplication, clustering and recommendation.
The figure at the top of the chapter shows what the space looks like. Paragraphs from the same article gather together, because paragraphs about one subject are relevant to the same questions.
Common take“Embeddings capture meaning.”
Sharper take“Embeddings capture whatever notion of similarity their training data defined. A general model can be mediocre on legal text or code, so I measure retrieval on my own corpus before I trust it.”
14.2Contrastive training
Pull matching pairs together and push the rest apart.
An embedding model is trained on pairs of texts that belong together, such as a question and the passage that answers it. For each question in a batch, its own passage is the positive example and every other passage in the batch is a negative. The loss rewards the model when the question’s vector is closer to its own passage than to the others. This is contrastive training, the same idea that CLIP used for images and captions (section 12.2).
To watch it work, I trained a small model on 87,599 question–paragraph pairs. The model is deliberately simple: it looks up a vector for each word and each three-letter fragment of a word, averages them, and normalizes the result to 96 dimensions. I tested it on questions about articles it never saw in training, counting how often the right paragraph, out of 20,963, appeared in its top ten.
The objective defines what the vectors mean. They encode “likely to be relevant to each other”, as judged by the training pairs. They do not encode truth, and they do not encode topic in any formal sense. Two consequences recur through this part of the guide: a model trained on web questions may rank poorly on contracts or code, and retrieval quality is something you measure, not assume.
Production embedding models differ from mine in scale, not in kind. They are transformer encoders trained on hundreds of millions of pairs, with negatives chosen to be hard: passages that look relevant and are not.
Common take“The embedding model understands my documents.”
Sharper take“It was trained to place questions near passages that answered them, on someone else’s data. Whether that transfers to my documents is an empirical question with a number for an answer.”
14.3Similarity metrics
Three formulas that agree once vectors are normalized.
| Metric | Measures | When it is used |
|---|---|---|
| Cosine similarity | The angle between two vectors, ignoring their lengths | The default for text |
| Dot product | Angle and length together | When the model was trained with it; length can then carry importance |
| Euclidean distance | Straight-line distance between the two points | Rare for text, common for images |
One fact simplifies the choice. If every vector is scaled to length 1, cosine similarity and the dot product are the same number, and Euclidean distance ranks results in the same order. So the production rule is short: normalize vectors when you store them and when you query, use the metric the model’s documentation names, and use it everywhere.
A second fact for calibration: scores are not comparable between models. A similarity of 0.8 from one model says nothing about 0.8 from another, so a rule such as “keep matches above 0.75” has to be re-tuned whenever the model changes.
Common take“I set the threshold to 0.8 because that means a strong match.”
Sharper take“A score only means something relative to the model that produced it. I pick thresholds from labeled examples and re-tune them if the model changes.”
14.4Bi-encoders and cross-encoders
Interaction traded for speed.
Bi-encoder: embeddings
Cross-encoder: reranking
An embedding model is a bi-encoder: the question and the document are encoded separately and compared afterward. That is what makes search fast, since documents are encoded once, ahead of time, and a query is compared with millions of stored vectors in milliseconds.
The price is that each document is compressed to a single point before any question has been seen. Fine distinctions blur inside that point: a 2019 policy against a 2021 policy, “covers” against “does not cover”. A cross-encoder avoids the blur by reading the question and one document together, so every word of one can attend to every word of the other. It is much more accurate and needs one full pass of the model per pair, which rules it out for searching a whole collection.
Production systems use both, in sequence: the bi-encoder cuts millions of documents down to a few dozen candidates, and a cross-encoder reorders those. Chapter 16 covers that second step, called reranking. Two designs sit between the extremes. Late interaction models such as ColBERT keep one vector per token and compare tokens at query time, which preserves detail at a higher storage cost. Learned sparse models such as SPLADE produce weighted word lists that can be served by a keyword index.
Common take“The top result of the vector search is the best match.”
Sharper take“Embedding search is a lossy compression of relevance. I use it to gather candidates, not to decide the final order.”
14.5Dimensions, storage and quantization
Vectors cost memory, and changing models means re-embedding everything.
Start with arithmetic. Ten million chunks at 1,536 dimensions, stored as 32-bit numbers, are 61 GB of vectors, and a search index adds roughly half as much again or more. That is why vector size is a budget decision. There are two ways to shrink it, and I measured both on my 96-dimensional model.
Fewer dimensions. I kept only the directions that carry the most variation:
| Dimensions kept | Bytes per vector | Right paragraph in the top 10 |
|---|---|---|
| 96 | 384 | 60.8% |
| 64 | 256 | 53.6% |
| 32 | 128 | 38% |
| 16 | 64 | 17.6% |
| 8 | 32 | 4.2% |
Every cut cost accuracy, because nothing in my training asked the model to put its most important information first. Models trained with Matryoshka learning are asked exactly that, and their vectors can be shortened to a half or a third with a loss of a few percent. Check whether your model supports it before truncating.
Fewer bits per dimension. This is quantization:
| Storage | Bytes per vector | Right paragraph in the top 10 |
|---|---|---|
| Four bytes per dimension, as trained | 384 | 60.9% |
| One byte per dimension | 96 | 60.8% |
| One bit per dimension | 12 | 33.2% |
| One bit per dimension, then the best 100 rescored with the full vectors | 12 | 51.4% |
Storing each dimension as one byte made the vectors four times smaller and changed nothing measurable. One bit per dimension was too coarse for a 96-dimensional model, and rescoring the best hundred candidates with the full vectors won back much of the loss. Binary codes hold up far better on models with a thousand or more dimensions, and the pattern, a cheap coarse search followed by exact rescoring, is the same funnel as in section 14.4.
Three operational facts complete the picture.
- Vectors from different models are incompatible. Different models, or different versions of one model, produce different spaces. Changing the model means re-embedding every document and re-tuning every threshold. Build the new index in full beside the old one and switch over in one step.
- Queries and documents may need different handling. Some models expect a prefix such as “query:” or “passage:”. Leaving it out lowers recall without any error.
- A vector averages what it is given. A long chunk that covers five topics becomes a blur of five. Section 15.3 returns to this.
- 4 bytes per dimension
- 1 byte
- 1 bit
Common take“Higher-dimensional embeddings are better, so we’ll use the largest.”
Sharper take“Dimensions are memory, and memory is money at ten million chunks. I measure recall at the full size, at a truncated size and with one-byte quantization, and I pay only for what moves the number.”
14.6Approximate search
Giving up a little recall for a lot of speed.
Exact search compares the query with every stored vector. The cost grows in step with the collection, which is fine at a hundred thousand vectors and impossible at a hundred million with many queries per second. Approximate nearest-neighbor search gives up the guarantee of finding the true top results in exchange for speed. Its quality is measured as recall: the share of the true nearest neighbors that the index returns.
The standard method is a layered graph called HNSW.
I built such an index over 103,344 sentence vectors and measured it against exact search.
| Search | Milliseconds per query | Share of the true top 10 found |
|---|---|---|
| Exact: compare with every vector | 0.56 | 100% |
| Approximate, effort 8 | 0.03 | 68.1% |
| Approximate, effort 16 | 0.05 | 79.8% |
| Approximate, effort 32 | 0.09 | 88.3% |
| Approximate, effort 64 | 0.17 | 94.1% |
| Approximate, effort 128 | 0.36 | 97.9% |
| Approximate, effort 256 | 0.70 | 99.5% |
At this size the conclusion is plain: exact search takes about half a millisecond, and the index is only worth having if you accept recall around 94%. That is the honest picture at a hundred thousand vectors. The balance changes with scale, because exact search slows in proportion to the collection while graph search slows roughly with its logarithm. At ten million vectors the same comparison is not close.
Three settings control the trade. The number of links per vector sets the size and quality of the graph. Build effort sets how carefully it is constructed. Search effort, the one varied above, is the dial you can turn in production without rebuilding. Two operating facts go with them: the graph lives in memory, which is where the storage arithmetic of section 14.5 becomes a server bill; and heavy deletion and updating degrades the graph over time, so rebuilding it is scheduled maintenance.
Common take“We need a vector index because we have embeddings.”
Sharper take“At a hundred thousand vectors, exact search took half a millisecond and returned the true answer. I add an approximate index when the collection or the query rate makes exact search too slow, and then I measure its recall.”
14.7Where to keep vectors
Your existing database until a measured limit forces a move.
| A vector extension in your existing database, such as pgvector in Postgres | A dedicated vector database | |
|---|---|---|
| Operations | No new system. Backups, access control and migrations are the ones you have | A new stateful service to run, secure and pay for |
| Filters and joins | Vector search inside an ordinary query, joined to your tables and consistent with them | Filters are supported, but the fields must be copied in and kept in sync |
| Comfortable scale | Up to millions of vectors at moderate query rates | Hundreds of millions, high query rates, sharding built in |
| Advanced features | Graph index, reduced-precision vectors, keyword search in the same query | More quantization options, multiple vectors per item, managed scaling |
The filter row matters more than it looks. Real queries are rarely “the nearest vectors”. They are “the nearest vectors among this customer’s documents, of this type, that this user may see”. When vectors live beside the rest of your data, that is one query against one source of truth. When they live elsewhere, permissions and deletions have to be copied across, and copies drift.
The rule that follows: start in the database you already run if your collection is in the millions or below. Move when you can name the number that forces it, such as a vector count, a query rate, or a memory requirement your database cannot meet.
Common take“RAG needs a vector database, so we’ll add one.”
Sharper take“A vector index is a feature of my data layer before it is a new database. I add infrastructure when a measured limit requires it.”
14.8Hybrid retrieval
Keyword search and embeddings fail on different queries.
Embeddings have a characteristic weakness: exact strings. A product code, an error number, a function name or a surname is compressed into a general region of the space, and the specific token, the only thing that mattered, is smoothed away. Keyword search has the opposite profile. The standard algorithm, BM25, scores a document higher when it contains the query’s words, gives more weight to rare words, and discounts repetition and long documents. It matches exact strings perfectly and misses a paraphrase completely.
BM25 fits in a few lines. This is the code used for every keyword result in this guide:
def bm25_index(texts, k1=1.2, b=0.75):
vocab, rows, cols, vals, lens = {}, [], [], [], []
for i, t in enumerate(texts):
c = Counter(tok(t)); lens.append(sum(c.values()))
for w, f in c.items():
rows.append(i); cols.append(vocab.setdefault(w, len(vocab))); vals.append(f)
N = len(texts); rows, cols, vals, lens = np.array(rows), np.array(cols), np.array(vals, dtype=np.float32), np.array(lens)
df = np.bincount(cols, minlength=len(vocab)); idf = np.log(1 + (N - df + 0.5) / (df + 0.5)) # rare words count for more
w = vals * (k1 + 1) / (vals + k1 * (1 - b + b * lens[rows] / lens.mean())) * idf[cols] # repeats saturate; long documents are discounted
return vocab, sp.csr_matrix((w, (cols, rows)), shape=(len(vocab), N))
def bm25_top(index, queries, k):
vocab, W = index; out = np.zeros((len(queries), k), dtype=np.int64)
for i, q in enumerate(queries):
ids = [vocab[w] for w in set(tok(q)) if w in vocab]
s = np.asarray(W[ids].sum(0)).ravel() if ids else np.zeros(W.shape[1])
top = np.argpartition(-s, k)[:k]; out[i] = top[np.argsort(-s[top])]
return out
def rrf(lists, k_out=20, c=60):
out = np.zeros((len(lists[0]), k_out), dtype=np.int64)
for i in range(len(lists[0])):
sc = {}
for L in lists:
for r, d in enumerate(L[i]):
sc[d] = sc.get(d, 0.0) + 1.0 / (c + r + 1)
out[i] = sorted(sc, key=sc.get, reverse=True)[:k_out]
return outHybrid retrieval runs both searches and merges the two ranked lists. The usual merge is reciprocal rank fusion: each document scores 1 ÷ (60 + its rank) in each list, and the scores are added. It works on ranks, so the two systems’ incomparable scores never have to be reconciled.
Here is how the three approaches did on the 2,000 held-out questions, and again after I introduced typing errors into about two words of each question.
| Method | Ranked first | In the top 10 | Ranked first, with typing errors | In the top 10, with typing errors |
|---|---|---|---|---|
| Keyword search (BM25) | 70.2% | 90.8% | 45.9% | 68.3% |
| Embeddings (this chapter’s model) | 32.9% | 60.9% | 16.7% | 39.6% |
| Both, fused with equal weight | 50.7% | 83.1% | 32.8% | 66.2% |
| Both, with keyword search weighted 3 to 1 | 56.5% | 89% | 39% | 70.2% |
These results deserve a careful reading, because they are not the story usually told.
- Keyword search won easily. The questions in this dataset were written by people looking at the paragraph, so they reuse its words. That is BM25’s best case.
- Fusing with a weak partner hurt. My embedding model is far weaker than a production one, and merging the lists with equal weight dragged the result below keyword search alone. The embeddings found the right paragraph when keyword search missed it for only 1.8% of questions.
- Typing errors changed the picture. Keyword search lost 22 points, since a misspelled word matches nothing. With keyword search weighted three to one, the hybrid edged ahead of either method alone.
Published results with strong embedding models show the same dependence on the queries. In the paper that introduced dense passage retrieval, embeddings beat BM25 by a wide margin on questions people had typed into a search engine, and lost to it on this very dataset. The durable lesson is that the two methods fail on different queries, and which one leads depends on how your users phrase things. Run both, set the weights on your own queries, and expect identifiers and rare names to lean on keywords while paraphrases lean on embeddings.
Common take“Vector search replaced keyword search.”
Sharper take“Embeddings are for meaning and keywords are for exact strings. I run both, fuse by rank, and tune the weights on real queries, because on some query sets the forty-year-old algorithm is the stronger half.”
14.9Choosing and adapting a model
A leaderboard is a starting point, and your data is the test.
The public reference for comparing embedding models is the Massive Text Embedding Benchmark (MTEB), a leaderboard covering retrieval, clustering, classification and other tasks in many languages. Use it to draw up a shortlist, and know what it cannot tell you.
- It is not your data. A model’s rank on general web text predicts little about tax law, source code or your internal jargon.
- Models are tuned toward it. A public benchmark becomes a target, and small differences near the top mean little.
- It leaves out the operating costs: vector size, maximum input length, speed, price, and whether you can run the model yourself.
The dependable procedure is to pick two or three candidates and compare them on your own labeled queries (section 14.10).
When no general model is good enough on a specialized corpus, an embedding model can be fine-tuned. The method is the contrastive training of section 14.2, continued on pairs from your domain: real queries with the passages that answered them, or questions that a language model writes for each of your passages. Hard negatives, passages that are close and wrong, make the training far more effective.
For multilingual collections, use a model trained to place different languages in one space, so that a question in one language can find a passage in another, and test each language you serve. Keyword search needs care here too, since splitting text into words works differently across languages.
Common take“We use the model at the top of the leaderboard.”
Sharper take“The leaderboard gave me three candidates. My own two hundred labeled queries chose between them, and the winner was not the one ranked first.”
14.10Measuring retrieval
It sets the ceiling for everything built on it.
If the passage containing the answer is not retrieved, the language model cannot be right. It will still answer, plausibly, from whatever it was given (section 2.9). Retrieval quality therefore caps the quality of the whole system, and it can be measured without a language model at all.
The harness is small. Collect 100 to 300 real queries. For each, record which chunks or documents should be retrieved. Then compute:
| Metric | Question it answers |
|---|---|
| Recall at k | For what share of queries is a correct item among the top k? |
| Mean reciprocal rank | How near the top is the first correct item, on average? |
| Precision at k | What share of the top k is relevant? Low precision means distractors in the prompt |
Read the numbers in this chapter that way. Keyword search put the right paragraph in the top ten for 90.8% of questions. So for 9.2% of questions, no model and no prompt could produce a grounded answer from ten retrieved paragraphs. Within the top hundred it found 96.8%, which is the most that a reranker working on those candidates could recover.
Every choice in this chapter, the model, the metric, the dimensions, the index settings, the fusion weights, can be tuned only against such a set. Build it before building the rest of the pipeline, and add to it from every failure you diagnose.
Common take“The answers are wrong, so we need a better language model.”
Sharper take“First I check whether the right passage was retrieved. If it was not in the context, the model never had a chance, and the fix is in retrieval.”
Key takeaways
- An embedding turns a text into one vector, so that search by meaning becomes search for nearby points.
- Embedding models are trained contrastively on pairs that belong together. The vectors encode “relevant to each other”, as that training data defined it.
- Normalize vectors and the common metrics agree. Scores are not comparable between models.
- A bi-encoder is fast because documents are encoded alone, and lossy for the same reason. Use it to gather candidates.
- One byte per dimension made vectors four times smaller at no measurable cost. Truncating dimensions cost accuracy on a model not trained for it.
- Approximate search trades recall for speed. On 103,344 vectors it reached 94% recall at a third of the time of exact search, and exact search took only half a millisecond.
- Keep vectors in the database you already run until a measured limit forces a move.
- Keyword search and embeddings fail on different queries. On questions that reuse the document’s words, BM25 found the right paragraph in the top ten 90.8% of the time against 60.9% for my embeddings.
- Changing the embedding model means re-embedding everything.
- Retrieval quality caps answer quality, and it can be measured with a few hundred labeled queries.
Check your understanding
-
Your team upgrades to a newer embedding model. The next morning, retrieval is badly wrong for a large share of queries, though not all. Nothing else changed. What happened, and how should the upgrade have been done?
Answer outline
Queries are being embedded with the new model while some or all stored vectors come from the old one. The two models produce different spaces, so distances between them are meaningless; documents re-embedded since the change still work, which is why only some queries fail. The upgrade should have built a complete new index with the new model alongside the old one, compared the two on the labeled query set, re-tuned any score thresholds, and then switched all traffic at once, keeping the old index until the new one was confirmed.
-
Your documentation search answers natural-language questions well. Users complain that pasting an error code such as E-4012 returns unrelated pages about errors in general. Explain the mechanism and the fix, and say how you would confirm the fix worked.
Answer outline
The system uses embeddings alone. An embedding places the code in a general “error” region, and the exact string, which is all that matters for this query, is lost. Add keyword search over the same chunks and fuse the two ranked lists by rank. Confirm by adding identifier queries to the labeled set and comparing recall before and after, for identifier queries and for natural-language ones separately, since the fusion weights that help one group can hurt the other.
-
You have three million chunks in Postgres. A colleague proposes moving to a dedicated vector database and switching to 3,072-dimensional embeddings “for quality”. Work out the storage, and say what you would measure before agreeing to either change.
Answer outline
Three million vectors at 3,072 dimensions and four bytes each are about 37 GB before the index, against about 12 GB at 1,024 dimensions, or 3 GB at 1,024 dimensions with one byte each. Measure recall on the labeled set at each size and precision; if the model supports shortened vectors, the smaller options may cost almost nothing. Three million vectors is well within what a vector extension handles, so the move needs a named reason: a measured query latency or rate that the current database cannot meet. Count the cost of keeping permissions and deletions in sync across two systems.
Further reading
- Jay Alammar and Maarten Grootendorst, Hands-On Large Language Models, chapters 2, 8 and 10: tokens and embeddings, semantic search, and training embedding models.
- Chip Huyen, AI Engineering, chapter 6: retrieval algorithms and how to evaluate them.
- Karpukhin et al. (2020), “Dense Passage Retrieval for Open-Domain Question Answering”: the paper behind section 14.2, including the comparison with BM25 across datasets.
- The pgvector documentation: a short, practical account of index types and their settings.