6.2Embeddings & vector search
How text becomes a point in space, how "similar" is measured, and how indexes like HNSW find the nearest neighbors among millions without checking them all.
Search by meaning, not by spelling
Type “how do I get my money back?” into a classic keyword search over a company handbook and you may get nothing, because the relevant page is titled “Refund policy” and never uses the words money or back. Keyword search matches spelling. People ask in meanings.
EmbeddingsEmbeddingA learned vector representing a token, word, image or document, arranged so that similar meanings get nearby vectors. fix this. You met token embeddings in embeddings & semantic space: vectors in which related words sit near each other. A text embedding model does the same for entire sentences or passages. It reads the text with a transformer and condenses it into a single vector, typically a few hundred to a few thousand numbers, such that “how do I get my money back?” and “Refund policy: returns within 30 days…” end up pointing in nearly the same direction.
Once every document is a vector, “find relevant documents” becomes “find the nearest points to the query’s point”. That idea, plus the engineering to do it at scale, is the retrieval half of retrieval-augmented generation, and it also powers recommendation, deduplication, clustering and semantic caching.
Imagine a city where every document lives at an address determined by what it is about: cooking blogs in one neighborhood, tax guides across town, and a “budget tracker in Python” on the street where finance meets programming. To answer a question, you work out the question’s address and knock on the nearest doors.
The address is the embedding, the street map is the vector space, and “nearest doors” is nearest-neighbor search. Knocking on every door in the city is brute force. Asking a well-connected local who points you to someone closer, who points you closer again, is a graph index like HNSW: a few long highway hops to the right district, then a short walk through the neighborhood.
How text embedding models are made
Most text embedding models are transformer encoders fine-tuned with contrastive learning (the same idea behind CLIP). Training data consists of pairs that should match, such as a question and the passage that answers it, or a title and its article. The model is rewarded when each pair’s vectors are more similar than the vectors of mismatched pairs in the same batch. Sentence-BERT (2019) and Dense Passage Retrieval (DPR, 2020) popularized the recipe; today’s models train on far larger mixtures of such pairs.
To get one vector for a passage, the model pools its per-token outputs, either by averaging them or by taking the vector at a special position. A few practical details matter more than they look:
- Asymmetric inputs. Many models expect a prefix or instruction that marks queries differently from documents (a short question and a long passage are different kinds of text). Use the model’s documented format.
- Dimension and truncation. Bigger vectors can hold more nuance but cost memory. Some models are trained “Matryoshka-style” so that the first 256 of 1,024 dimensions still work as a decent embedding on their own.
- Same model for both sides. Query and documents must be embedded by the same model. Vectors from two different models live in unrelated spaces.
- Context limit. Embedding models read a limited number of tokens, and one vector can only summarize so much. Long documents are split into chunks first (see RAG).
Public leaderboards such as MTEB compare models across retrieval, clustering and classification tasks, but scores on your own data are what count.
Measuring “close”: cosine, dot product, L2
Three measures dominate:
- Dot product : multiply matching coordinates and add. Large when the vectors point the same way and are long.
- Cosine similarityCosine similarityThe dot product of two vectors divided by the product of their lengths: the cosine of the angle between them, from −1 to 1.: the dot product divided by both lengths. It depends only on the angle between the vectors, from −1 (opposite) through 0 (unrelated) to 1 (same direction).
- Euclidean (L2) distance: the straight-line distance between the two points. Smaller is closer.
These can disagree. A long vector that points slightly off can win on dot product but lose on cosine. But if you normalize every vector to length 1, all three produce the same ranking, because for unit vectors the squared L2 distance is just . That is why many systems normalize at ingestion and then use whichever operation their index computes fastest. Use the measure the embedding model was trained for; its documentation will say.
Click anywhere to move the query (◆). Dashed ring = unit circle; dashed ray = query direction.
- 0.999 Sourdough bread for beginners
- 0.995 Five soups for cold evenings
- 0.995 Easy weeknight pasta
- 0.978 A rich tomato sauce
Ochre edges = hops on the sparse upper layers (long jumps); blue = the beam search on the dense bottom layer. Faded points were never compared with the query. With 40 documents the savings are small; turn on the 400 background docs to see the walk skip most of the corpus.
Things to try:
- Cosine vs dot product. Pick “beginner bread recipe”. With cosine, the nearest cooking documents by angle win. Switch to dot product and long vectors far out on the edge get a boost, even slightly off-topic ones. Switch to L2 and short vectors near the query’s position win instead.
- Normalize. Every point snaps onto the unit circle, and now all three measures return the same list in the same order.
- Border queries. “python for space simulations” lands between Programming and Space, and the top results mix both topics. Embeddings capture blends, not just categories.
- Graph walk with 440 documents. Turn on the background documents and animate. The walk computes far fewer than 440 distances. Then drop ef to 1 and watch recall sometimes fall below 100%: that’s the “approximate” in approximate nearest neighbor.
Exact search and why it gets expensive
The simplest index is no index: compare the query with every stored vector and keep the top . This exact kNN search is perfectly accurate, and for up to a few hundred thousand vectors it is often fast enough, especially as one matrix multiplication on a GPU.
The cost grows linearly with the collection. Ten million passages with 1,024-dimensional float32 embeddings occupy bytes ≈ 41 GB, and every query touches all of it, about multiply-adds. At hundreds of queries per second, that becomes the bottleneck. Approximate nearest neighborApproximate nearest neighbor (ANN) searchFinding vectors that are very probably among the closest to a query without comparing against every stored vector, trading a little recall for a large speedup. (ANN) indexes accept a small chance of missing a true neighbor in exchange for touching only a small fraction of the data. Quality is reported as recall@k: the fraction of the true top- that the index actually returned.
HNSW: hopping through a small world
HNSWHNSWHierarchical Navigable Small World graph: an ANN index that links each vector to nearby vectors in several layers and finds neighbors by greedily walking the graph from a coarse top layer down. (Hierarchical Navigable Small World, Malkov & Yashunin, 2016) is the most widely used ANN index. It builds a graph in which each vector links to a handful of nearby vectors, and stacks several such graphs in layers:
- The bottom layer contains every vector, each linked to its close neighbors.
- Each higher layer keeps a random, exponentially thinning subset of the vectors, so links on the upper layers span long distances, like highways over local streets.
- Search starts at an entry point on the top layer, greedily hops to whichever neighbor is closest to the query until no neighbor is closer, then drops a layer and repeats. On the bottom layer it runs a small beam search, keeping the best
efcandidates found so far.
The work grows roughly logarithmically with the collection size instead of linearly. The knobs are M (links per node: more memory, better recall), efConstruction (effort spent building) and efSearch (beam width at query time: the recall-versus-speed dial you played with in the demo). HNSW’s weaknesses are memory, since the graph lives alongside full vectors and usually in RAM, and the awkwardness of deleting entries.
IVF and product quantization
Two other classic ideas, often combined, come from the FAISS library’s lineage:
- IVF (inverted file index). Cluster all vectors with k-means into, say, 4,096 cells. At query time, find the few cells whose centroids are nearest to the query (
nprobeof them) and search only inside those. More probes means more recall and more work. - Product quantizationProduct quantization (PQ)Compressing vectors by splitting each into sub-vectors and replacing every sub-vector with the id of its nearest centroid from a small learned codebook. (PQ). Compress each vector by splitting it into sub-vectors and replacing each sub-vector with the id of its nearest centroid from a small codebook of 256 entries, which fits in one byte. A 1,024-dimensional float32 vector (4,096 bytes) with becomes 64 bytes, a 64× saving, and distances can be estimated directly from the codes with lookup tables. The price is some accuracy, which is often won back by re-scoring the top candidates with full vectors.
A vector databaseVector databaseA store optimized for finding the vectors nearest to a query vector, usually with approximate nearest-neighbor indexes. packages these indexes with the unglamorous necessities: storage, updates and deletes, metadata filters (“only documents from 2025, only this customer”), replication and access control.
Hybrid search and reranking
Dense embeddings are great at paraphrase and terrible at exact identifiers. Ask for error code E-4012, a part number or a rare surname, and the embedding may place it near vaguely similar codes. Old-fashioned keyword ranking handles these perfectly.
The standard keyword scorer is BM25BM25A classic keyword-ranking formula that scores documents by how often they contain the query's terms, weighting rare terms more and damping long documents.. It rewards documents that contain the query’s terms, gives more weight to rare terms (inverse document frequency), lets repeated occurrences count with diminishing returns, and discounts very long documents. Hybrid searchHybrid searchCombining keyword search (such as BM25) with vector search and merging the two ranked lists, so exact terms and paraphrases are both found. runs BM25 and vector search side by side and merges the two ranked lists. A simple and robust merge is reciprocal rank fusion: each document scores over the lists it appears in, so a document ranked well by either method rises.
Finally, a rerankerRerankerA slower, more accurate model (often a cross-encoder) that rescores a short list of retrieved candidates by reading the query and each document together. fixes the order. Embedding search uses a bi-encoder: query and document are embedded separately, which is what makes precomputation and fast search possible, but the two texts never “see” each other. A cross-encoder reranker reads the query and one candidate together through a full transformer and outputs a relevance score. That is far more accurate and far too slow to run over millions of documents, so the usual pipeline is: retrieve ~50–200 candidates cheaply, rerank them, and keep the top 5–10.
MATH CORNER · optionalCosine, dot and L2 on small vectors
For vectors and :
If , the last identity becomes : smaller distance ⇔ larger cosine ⇔ larger dot product. Same ranking.
Worked example. Query and two documents , . Lengths: , , .
| dot | cosine | L2 distance | winner | |
|---|---|---|---|---|
| vs | 2.000 | 0.707 | 1.414 | dot picks |
| vs | 0.700 | 0.990 | 0.922 | cosine and L2 pick |
Document wins on dot product only because it is long. Now normalize: , , .
| dot = cosine | L2 distance | |
|---|---|---|
| vs | 0.707 | 0.765 |
| vs | 0.990 | 0.141 |
All measures now agree on .
PQ memory. A -dimensional float32 vector costs bytes. PQ with sub-vectors and 256 centroids per sub-space stores bytes (plus small shared codebooks). For , : bytes. Ten million vectors shrink from ~41 GB to ~0.64 GB.
In code
Exact search is three lines of NumPy once vectors are normalized; an HNSW index in FAISS is barely more.
import numpy as np, faiss
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("all-MiniLM-L6-v2") # 384-dim embeddings
docs = ["Refund policy: returns within 30 days...", "Sourdough for beginners...", ...]
D = model.encode(docs, normalize_embeddings=True) # shape (N, 384), unit length
q = model.encode(["how do I get my money back?"], normalize_embeddings=True)
# Exact kNN: one matrix-vector product, then take the k largest cosines
scores = D @ q[0]
top = np.argsort(-scores)[:5]
# Approximate: HNSW graph with M=32 links per node, inner-product metric
index = faiss.IndexHNSWFlat(D.shape[1], 32, faiss.METRIC_INNER_PRODUCT)
index.hnsw.efSearch = 64 # beam width: recall vs speed
index.add(D.astype("float32"))
sims, ids = index.search(q.astype("float32"), 5)
- “Cosine similarity of 0.8 means 80% relevant.” Similarity scores are only meaningful relative to each other for one model. Different models have very different score distributions, so fixed thresholds rarely transfer.
- “Approximate search returns approximately-right garbage.” Well-tuned ANN indexes routinely reach recall@10 above 0.95 while touching a tiny fraction of the data. The misses are usually near-ties.
- “Vector search makes keyword search obsolete.” Exact identifiers, rare names and codes are often better served by BM25. Hybrid search usually beats either alone.
- “Bigger embedding dimension is always better.” Beyond a point, extra dimensions add memory and latency for little gain on your data. Measure recall on your own queries.
- “I can swap embedding models and keep my index.” Every model defines its own space. Changing the model means re-embedding every document.
Check your understanding
Q1.All your stored vectors and queries are normalized to length 1. Which statement is true?
Q2.In HNSW, what does increasing efSearch do?
Q3.Users search your docs for error codes like
E-4012and dense retrieval keeps returning similar-looking but wrong codes. Best fix?Q4.Why rerank with a cross-encoder instead of using it for the whole search?
Further reading
- paperEfficient and robust approximate nearest neighbor search using HNSW graphs — Malkov & Yashunin, the HNSW paper.
- paperSentence-BERT: Sentence Embeddings using Siamese BERT-Networks — The paper that made sentence embeddings practical.
- paperDense Passage Retrieval for Open-Domain Question Answering — Karpukhin et al.: contrastively trained dual encoders beat BM25 on QA retrieval.
- paperThe Faiss library — Douze et al.: IVF, PQ, HNSW and the trade-offs between them, from the library's authors.
- paperMTEB: Massive Text Embedding Benchmark — How embedding models are compared across many tasks.