Module 2 · Vector databases
ANN indexes: HNSW, IVF, Product Quantization
6 min read
Finding the k vectors closest to a question is trivial over 67 passages: compute every similarity and sort. Over 10 million passages, that exact search costs hundreds of milliseconds per query and no longer scales. Vector databases therefore use approximate indexes (ANN, Approximate Nearest Neighbors): much faster, at the price of a few missed neighbors. This lesson explains the three main families — HNSW, IVF, Product Quantization — and measures them with FAISS.
The principle: trading a little accuracy for a lot of speed
An ANN index only examines a small part of the vectors. Its quality is measured against exact search: an index's recall@10 is the share of the 10 true nearest neighbors it finds. An index with 0.95 recall misses on average one neighbor out of twenty.
This is a crucial and often ignored point: the index's recall adds up to the embedding model's errors. If the index loses 30% of the true neighbors, your RAG silently loses relevant documents, without any error being reported. An index is therefore tuned by measuring, never blindly.
HNSW: a navigable graph
HNSW (Hierarchical Navigable Small World) connects each vector to its close neighbors in a multi-level graph. The upper levels, sparsely populated, act as highways; level 0 contains all the vectors. A search starts at the top, goes down level by level while getting closer to the target, then explores locally.
Three parameters:
| Parameter | Role | Effect |
|---|---|---|
M | Number of neighbors per node | More = better recall, more memory |
efConstruction | Build effort | More = better graph, slower build |
efSearch | Candidates explored per query | The main knob: more = better recall, slower query |
HNSW is the default index of almost every vector database: excellent recall, very fast, and it accepts incremental inserts. Its drawbacks: it takes a lot of memory (the vectors plus the graph), and deletions are expensive (nodes are often marked deleted and cleaned up later).
IVF: partitioning the space
IVF (Inverted File) groups vectors into nlist partitions with k-means. At search time, only the nprobe partitions whose centers are closest to the question are scanned.
nlist: number of partitions (on the order of √n to 4√n in practice).nprobe: partitions explored per query, the main knob.
IVF requires training (the k-means) on a representative sample. If the data changes a lot after training, partitions become unbalanced and quality drops: retraining is needed. In return, IVF is more compact than HNSW and combines well with compression.
Product Quantization: compressing vectors
PQ splits each vector into m sub-vectors and replaces each one with the index of the nearest center in a small codebook (256 centers = 1 byte). A 384-dimension float32 vector (1,536 bytes) becomes 48 bytes with m=48. Distances are computed approximately, from precomputed tables. PQ is often combined with IVF (IVF-PQ) for very large volumes.
Measuring: FAISS on 50,000 vectors
Prism compares these indexes with FAISS, always against exact search:
for ef in (16, 64, 256): # efSearch : taille de la liste de candidats explorée par requête
hnsw = faiss.IndexHNSWFlat(dim, 32, faiss.METRIC_INNER_PRODUCT) # M = 32 voisins par nœud
hnsw.hnsw.efConstruction = 100
hnsw.hnsw.efSearch = ef
results.append(_measure(f"HNSW M=32 efSearch={ef}", hnsw, base, queries, truth, train=False))
Measured results (50,000 vectors of 384 dimensions, 200 queries, CPU):
| Index | recall@10 | ms/query | bytes/vector |
|---|---|---|---|
| Flat (exact) | 1.000 | 0.58 | 1,536 |
| HNSW M=32, efSearch=16 | 0.949 | 0.016 | 1,808 |
| HNSW M=32, efSearch=64 | 1.000 | 0.026 | 1,808 |
| HNSW M=32, efSearch=256 | 1.000 | 0.062 | 1,808 |
| IVF nlist=256, nprobe=4 | 0.932 | 0.027 | 1,552 |
| IVF nlist=256, nprobe=32 | 1.000 | 0.174 | 1,552 |
| IVF-PQ m=48, nprobe=32 | 0.593 | 0.027 | 72 |
Reading:
- HNSW is 20 times faster than exact search with perfect recall from
efSearch=64, for 18% more memory (the graph). - IVF also reaches perfect recall, but it needs to scan 32 partitions out of 256 and becomes slower than HNSW.
- IVF-PQ divides memory by 21… and only finds 59% of the true neighbors. Aggressive compression comes at a price, and it requires re-ranking the candidates with the full vectors (lesson 2.4).
The synthetic data trap
These vectors are synthetic, and generating them was a lesson in itself. A first version used random noise in 384 dimensions: HNSW only found 48% of the true neighbors there. In high dimension, random points are almost equidistant: the very notion of "nearest neighbor" loses its meaning, and no approximate index looks good.
Real embeddings are very different: they occupy a structure of low intrinsic dimension (themes, topics) embedded in the 384-dimension space. Prism therefore generates thematic clusters in a 32-dimension latent space, projected into 384:
latent = centers[labels] + 0.5 * rng.normal(size=(n, intrinsic))
vectors = latent @ projection + 0.05 * rng.normal(size=(n, dim))
The practical conclusion goes beyond the exercise: tune your indexes on your real vectors. An ANN benchmark published on another dataset does not tell you which efSearch to choose for yours.
Tuning an index in production
- Sample a few hundred real queries and compute their true neighbors by exact search (once, offline).
- Measure recall@k and latency for several values of the search parameter (
efSearch,nprobe). - Choose the smallest value that reaches your recall target (for example 0.98).
- Measure again when the volume or the distribution of the data changes.
Beyond a few tens of millions of vectors, other families come into play: on-disk indexes (DiskANN and its variants) that keep most of the data out of RAM, or GPU indexes. The measurement principles stay the same.
Key takeaways
- An ANN index trades a little recall for a lot of speed; its recall is measured against exact search.
- HNSW (graph): the default, fast and accurate, memory-hungry; tune
efSearch.- IVF (partitions): compact, needs training; tune
nprobe.- PQ compresses heavily but loses a lot of recall: combine it with exact re-ranking.
- Tune your indexes on your real vectors: random high-dimensional data skews everything.
Practice
- Run
examples/02_ann_indexes.pyand addefSearch=32: where is the threshold for perfect recall? - Switch IVF-PQ to
m=96: what do you gain in recall, what do you lose in memory? - Generate vectors with
intrinsic=384(near-uniform noise) and watch HNSW's recall drop.