Skip to content
LearnAI

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.

⏱ 14 minIntermediate

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.

ANALOGY· A city where every document has an address

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:

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 2−2cos⁡2 - 2\cos. 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.

INTERACTIVE2D vector-search playground
Query:
SportsHealthCookingFinanceProgrammingSpaceMoviesMusicOffside rule in soccer explainedBasketball's three-point revolutionTennis scoring, demystifiedHow league tables workTraining for your first 10K raceHow much sleep do adults need?A 20-minute home workoutStretching before runningHeart rate zones explainedEating more fiber, simplyEasy weeknight pastaSourdough bread for beginnersA rich tomato sauceFive soups for cold eveningsKnife skills in the kitchenIndex funds vs stock pickingBuilding a monthly budgetHow compound interest worksUnderstanding your tax returnWriting a budget tracker in PythonPython list comprehensionsDebugging JavaScript in the browserWhat is an API?Git branching basicsOrbital mechanics in PythonWhy Mars is redHow rockets reach orbitThe life cycle of a starWhat telescopes see in infraredPhases of the moonClassic sci-fi movies rankedWhat a film director actually doesThe art of the movie trailerHow the Oscars are votedHow film scores create tensionLearning your first guitar chordsWhy jazz swingsPiano practice routinesMixing a home recordingWarm-up playlists for the gym

Click anywhere to move the query (◆). Dashed ring = unit circle; dashed ray = query direction.

Similarity
Top 4 for “beginner bread recipe” (exact, by cosine)
  1. 0.999 Sourdough bread for beginners
  2. 0.995 Five soups for cold evenings
  3. 0.995 Easy weeknight pasta
  4. 0.978 A rich tomato sauce
Graph search (HNSW-style) vs brute force
brute force: distances
40
graph walk: distances
27
recall@4 of walk
100%
current layer
top = 2

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.

Forty documents placed as 2D points (a hand-curated cartoon of a real high-dimensional space). Pick or type a query, switch the similarity measure, normalize, change k, then animate the graph walk and compare its distance count with brute force.

Things to try:

  1. 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.
  2. Normalize. Every point snaps onto the unit circle, and now all three measures return the same list in the same order.
  3. Border queries. “python for space simulations” lands between Programming and Space, and the top results mix both topics. Embeddings capture blends, not just categories.
  4. 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 kk. 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 107×1024×410^7 \times 1024 \times 4 bytes ≈ 41 GB, and every query touches all of it, about 101010^{10} 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-kk 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 ef candidates 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:

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 ∑1/(60+rank)\sum 1/(60 + \text{rank}) 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 qq and dd:

dot(q,d)=∑iqidi,cos⁡(q,d)=q⋅d∥q∥ ∥d∥,∥q−d∥2=∥q∥2+∥d∥2−2 q⋅d.\text{dot}(q,d) = \sum_i q_i d_i, \qquad \cos(q,d) = \frac{q\cdot d}{\lVert q\rVert\,\lVert d\rVert}, \qquad \lVert q-d\rVert^2 = \lVert q\rVert^2 + \lVert d\rVert^2 - 2\, q\cdot d .

If ∥q∥=∥d∥=1\lVert q\rVert = \lVert d\rVert = 1, the last identity becomes ∥q−d∥2=2−2cos⁡(q,d)\lVert q-d\rVert^2 = 2 - 2\cos(q,d): smaller distance ⇔ larger cosine ⇔ larger dot product. Same ranking.

Worked example. Query q=(1,1)q = (1, 1) and two documents a=(2,0)a = (2, 0), b=(0.3,0.4)b = (0.3, 0.4). Lengths: ∥q∥=1.414\lVert q\rVert = 1.414, ∥a∥=2\lVert a\rVert = 2, ∥b∥=0.5\lVert b\rVert = 0.5.

dotcosineL2 distancewinner
qq vs aa2.0000.7071.414dot picks aa
qq vs bb0.7000.9900.922cosine and L2 pick bb

Document aa wins on dot product only because it is long. Now normalize: q^=(0.707,0.707)\hat q = (0.707, 0.707), a^=(1,0)\hat a = (1, 0), b^=(0.6,0.8)\hat b = (0.6, 0.8).

dot = cosineL2 distance =2−2cos⁡=\sqrt{2-2\cos}
q^\hat q vs a^\hat a0.7070.765
q^\hat q vs b^\hat b0.9900.141

All measures now agree on bb.

PQ memory. A DD-dimensional float32 vector costs 4D4D bytes. PQ with mm sub-vectors and 256 centroids per sub-space stores mm bytes (plus small shared codebooks). For D=1024D = 1024, m=64m = 64: 4096→644096 \to 64 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)
COMMON MISCONCEPTIONS
  • “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

0/4 answered
  1. Q1.All your stored vectors and queries are normalized to length 1. Which statement is true?

  2. Q2.In HNSW, what does increasing efSearch do?

  3. Q3.Users search your docs for error codes like E-4012 and dense retrieval keeps returning similar-looking but wrong codes. Best fix?

  4. Q4.Why rerank with a cross-encoder instead of using it for the whole search?

Further reading

Progress is saved in this browser only.
Type to search across all lessons and glossary terms.