How vector databases find nearest neighbours without checking everything. Step through HNSW, escape an NSW dead end, probe IVF cells, compress with PQ and compare recall against cost.
1Exact search measures everything
To find the nearest vectors for certain, compare the query with every stored vector. Fine for thousands; with millions of 768-number embeddings and many queries a second, far too slow.
2Graphs: hop toward the query
HNSW links every vector to a few near neighbours, plus a sparse top layer of long links. Start anywhere, keep hopping to whichever neighbour is closer, and you arrive near the query after measuring only a few vectors.
3Cells and codes: search less, store less
IVF sorts the vectors into cells around k-means centres and searches only the cells nearest the query. Product quantisation squeezes each vector into a few bytes of codes, so millions fit in memory.
The baseline
Brute force: measure everything
RAG, recommendations and semantic search all ask the same question: which stored vectors are nearest to this one? The exact answer is easy: measure the distance to every vector and keep the k smallest. Here 120 points stand in for embeddings (real ones have hundreds of dimensions). Click anywhere to move the query.
- Distances measured
- 120
- Recall
- 100%
Always right, and the work grows in a straight line with the data: n vectors × d numbers per query. With a million 768-number embeddings that's 768 million multiply-adds for every question.
Approximate nearest neighbour (ANN) indexes give up a little accuracy, measured as recall (the share of the true top k they return), to measure far fewer vectors. Everything below is a different way to do that.
Graphs, part 1
NSW: a navigable small world
Link each point to its 3 nearest neighbours as it is added. Early points were added when the space was empty, so their links are long: highways across the map. That mix of short and long links is a “small world”: any point is a few hops from any other. To search, start at the first point and keep hopping to whichever neighbour is closer to the query.
- Measured
- 24 of 120
- Found the nearest?
- No
Stuck in a local minimum: none of this point's neighbours is closer to the query, yet the true nearest (green ring) is elsewhere. Greedy search can't see past it. Try the beam.
Click the plot to try your own query. Big NSW graphs have a second problem: early nodes collect huge numbers of links, so each hop gets expensive.
Graphs, part 2
HNSW: layers of small worlds
HNSW fixes both problems with a hierarchy, like a skip list. Every point is on layer 0, with short links. A random few also join layer 1, fewer still layer 2, and so on, each layer a sparser graph with longer links. Search starts at the top, takes big greedy hops, drops a layer, takes smaller hops, and finishes with a beam search of width ef on layer 0. Step through it, change ef, or click to move the query.
Press Start to search for the 3 nearest neighbours of the query, from the top layer down.
Building it
The three settings
Why it's the default
Partitions
IVF: search only the nearest cells
An inverted file index runs k-means once to split the vectors into cells (here 9), and stores a list of members for each cell. A query is compared with the 9 centres, then only the vectors in the nearest nprobe cells are measured.
- Measured
- 18 of 120
- Recall@3
- 33%
A true neighbour sits just across a cell wall, in a cell that wasn't searched. Raise nprobe.
Typical settings: about √n cells (a million vectors → ~1,000) and nprobe of 1–5% of them. Cheap to build and small in memory; recall drops at cell edges.
Compression
Product quantisation: vectors as a few bytes
A million 768-number vectors are 3 GB of floats. Quantisation stores each vector as the id of the nearest entry in a small codebook. In 2-D below, each point is replaced by its nearest diamond: with 16 diamonds, a 4-bit code. Distances are then computed to the diamonds, a little off, but very cheap.
- Bits per point
- 4 (not 64)
- Avg error²
- 0.337
One codebook for a 768-dimension space would need billions of entries. The “product” trick: cut the vector into m pieces (say 96 pieces of 8 numbers) and give each piece its own 256-entry codebook. 96 one-byte codes, and 256⁹⁶ possible combinations.
One 8-number vector, cut into 4 pieces, each piece replaced by a code:
At query time, measure the query's pieces against each codebook once (a small table), then each stored vector's distance is just m table lookups added up.
Hashing
LSH: random planes as a hash
Locality-sensitive hashing draws random planes. Each one gives a bit: which side is the vector on? Vectors with the same bits share a bucket, and only the query's bucket is searched. Near vectors usually agree on every bit; far ones rarely do. The shaded region is the query's bucket.
- Measured
- 54 of 120
- Recall@3
- 100%
More planes, smaller buckets: less to measure, but a true neighbour on the wrong side of any one plane is lost. Real LSH keeps several tables with different random planes and searches the query's bucket in each, so a neighbour split off in one is caught in another.
Simple, with no training and easy updates, but it usually needs more memory and gives lower recall than HNSW or IVF on real embeddings.
Measured, not claimed
The recall–cost trade-off
Pictures in 2-D only go so far. Here are the three indexes built for real on 2,000 clustered vectors in 32 dimensions, with 40 queries. For each setting: the share of each query's true top 10 returned, and the share of vectors measured to get it.
Building three indexes over 2,000 vectors and timing 40 queries…
In practice
Choosing an index
| Index | Recall | Memory | Build | Adding data | Good for | Found in |
|---|---|---|---|---|---|---|
| Flat (brute force) | Exact | Vectors only | None | Instant | Under ~100k vectors; checking other indexes | Every library |
| HNSW | Very high | Vectors + links (high) | Slow | Easy; deletes awkward | The default for in-memory search | Qdrant, Weaviate, pgvector, Elasticsearch, Milvus, Faiss |
| IVF | Good; drops at cell edges | Low | Fast (k-means) | Easy; retrain cells if data drifts | Large sets, tighter memory | Faiss, Milvus, pgvector (IVFFlat) |
| IVF-PQ | Lower; fix with re-ranking | Very low | Moderate | Easy | Hundreds of millions of vectors | Faiss, Milvus |
| LSH | Lower | High (many tables) | Instant | Easy | Streaming data, theory | Faiss, older systems |
| DiskANN / ScaNN | Very high | Mostly on SSD / compressed | Slow | Varies | Billions of vectors | Milvus, Azure, Google (ScaNN) |
Match the metric
Filtering is hard
Measure your recall
Why trees don't work here
See vector search used in a full pipeline in RAG and the Advanced RAG course.
No magic, just arithmetic
The maths, step by step
A realistic index: 1,000,000 embeddings of 768 numbers each. What does each method cost per query, and why does each one work?
- 1
Brute force
One distance per vector, and each distance is d multiply-adds.multiply-adds per query = 1,000,000 × 768 = 768000000.0000
768,000,000 operations for every single query: about 3 GB of floats read each time.
- 2
IVF
1,000 cells of about 1,000 vectors. Measure the query against the cell centres, then scan only the nearest 10 cells.vectors measured = 1,000 centres + 10 × 1,000 = 11000.0000
share of brute force = 11,000 ÷ 1,000,000 = 0.0110
About 1% of the work. The risk: a true neighbour sitting just across a cell wall, in a cell you didn't probe.
- 3
HNSW layers
Each new point reaches layer l with probability M^−l (here M = 16), so each layer keeps about 1/16 of the one below. Search drops through about log_M(n) layers.nodes on layer 1 = 1,000,000 × 16^−1 = 62500.0000
nodes on layer 2 = 1,000,000 × 16^−2 = 3906.2500
nodes on layer 3 = 1,000,000 × 16^−3 = 244.1406
nodes on layer 4 = 1,000,000 × 16^−4 = 15.2588
nodes on layer 5 = 1,000,000 × 16^−5 = 0.9537
layers, log₁₆(n) = ln 1,000,000 ÷ ln 16 = 4.9829
A handful of long hops on the sparse top layers, then a local beam search at the bottom: the cost grows roughly with log n, not n.
- 4
Product quantisation memory
Cut each vector into 96 pieces of 8 numbers; replace each piece by the id (one byte) of its nearest centroid among 256.bytes per vector, floats = 768 × 4 = 3072.0000
bytes per vector, PQ = 96 × 1 = 96.0000
whole index, floats (GB) = 1,000,000 × 3072 ÷ 10⁹ = 3.0720
whole index, PQ (GB) = 1,000,000 × 96 ÷ 10⁹ = 0.0960
- 5
Why LSH finds near vectors
A random plane separates two vectors at angle θ with probability θ / 180°. Near vectors (small θ) usually agree on every bit; far ones rarely do.one bit agrees, θ = 30° = 1 − 30/180 = 0.8333
all 8 bits agree = 0.8333^8 = 0.2326
caught by 1 of 8 tables = 1 − (1 − 0.2326)^8 = 0.8797
same, far vector θ = 90° = 1 − (1 − 0.5^8)^8 = 0.0308
More bits make buckets smaller (fewer candidates, but near vectors get split up); more tables catch them again.
Keep going
Resources
Hand-picked places to go deeper. They're all free to read or watch, and they open in a new tab.
How it works: Vector Search (HNSW)
Step by step
- The search path and measured vectors
- Best found so far
- True nearest neighbours
Press Start or Step: the step the animation is on lights up below.
- 1
Enter at the top
Start at the single entry point on the highest layer, which has only a handful of nodes and long links.
cur = entry_point; L = top_layer - 2
Greedy hops
On an upper layer, move to whichever neighbour is closer to the query; stop when none is.
while some nb in N_L(cur) is closer: cur = nb - 3
Drop a layer
Keep the same node and move down to the next, denser layer with shorter links.
L = L - 1 - 4
Beam search on layer 0
Keep the ef best nodes found; repeatedly expand the nearest unexpanded candidate's neighbours; stop when the next candidate is worse than the worst kept.
W = search_layer(q, cur, ef, layer=0) - 5
Return the k nearest
The k best of the ef kept. Bigger ef means more distances measured and higher recall.
return top_k(W)
Vector search finds the stored vectors nearest to a query vector. Exact (brute-force) search measures all n vectors of d numbers: always right, but O(n·d) per query. Approximate nearest-neighbour (ANN) indexes measure far fewer vectors and return most of the true neighbours; the share returned is the recall.
Graph indexes link each vector to nearby ones. NSW is one such graph: greedy hops toward the query, but it can stop in a local minimum. HNSW stacks sparser graphs on top (each point reaches layer l with probability M^−l), searches greedily from the top, and finishes with a beam search of width ef on the bottom layer.
Other families: IVF splits the space into k-means cells and searches only the nprobe nearest cells; product quantisation (PQ) compresses each vector into a few bytes of codebook ids; LSH hashes with random hyperplanes so near vectors tend to share a bucket. Production systems combine them, such as IVF-PQ with re-ranking.
Where you'll meet it
- Retrieval for RAG, semantic search, recommendations and de-duplication over embeddings, once brute force is too slow (roughly beyond 100k vectors or for many queries a second).
- HNSW when the index fits in memory and recall matters; IVF or IVF-PQ when memory is tight or the collection is huge; brute force for small sets and for measuring the recall of any index.
- Interview favourites: “how does HNSW work?”, “what do M, efConstruction and ef do?”, “HNSW vs IVF?”, “what is product quantisation?”, “how do you measure recall?”, “why don't KD-trees work in high dimensions?”.
HNSW visits a few nodes per layer across about log_M(n) layers, plus an ef-wide beam at the bottom; each visit measures one d-dimensional distance. Building costs about n · log n · efConstruction distance checks. IVF measures nlist centres plus about n · nprobe / nlist vectors; PQ stores m bytes per vector instead of 4d.