ANN indexes: HNSW, IVF, PQ

In one sentence

Exact nearest-neighbor search scans every vector; ANN indexes visit a tiny fraction and accept missing a few true neighbors. HNSW is the default, IVF and PQ trade recall for memory, efSearch/nprobe are the dials.

Analogy: Finding a house by asking for directions: first the right highway exit, then the street, then door to door. You never check every house, and once in a while you miss the best one.

HNSW descends a graph; IVF-PQ scans a few compressed clusters. efSearch and nprobe set how much you look, and therefore recall versus latency.

How it works

  • Measure quality as recall@k: the share of the true top-k neighbors the index actually returned.
  • HNSW is a layered graph searched by greedy hops: best recall per millisecond, but RAM-heavy and slow to build.
  • IVF splits vectors into nlist k-means clusters and scans only the nprobe closest, missing neighbors across borders.
  • PQ stores compact codes, 32–64× smaller, so it usually ships as IVF-PQ plus rescoring with full vectors.
  • Sweep efSearch on real queries against brute-force results; keep the smallest value that hits your recall target.

Check yourself

Answer to mark it learned; your answers aren't scored.

Your RAG retrieves top-20 from an HNSW index, and answer quality is poor. The team wants to switch embedding models. You find the index runs with efSearch = 8. What do you do first?

Go deeper

Full explanation

Exact k-nearest-neighbor search compares the query with all N vectors: O(N·d). At 10M × 768 dims that is ~7.7 billion multiply-adds and ~31 GB of memory read per query. ANN (approximate nearest neighbor) indexes look at a tiny fraction and accept missing a few true neighbors. The quality metric is recall@k: the share of the true top-k you got back.

  • HNSW (Hierarchical Navigable Small World): a layered proximity graph. Search enters the sparse top layer, hops greedily toward the query and descends to layer 0, which holds every vector. Knobs: M (links per node), efConstruction (build effort) and efSearch (candidate list at query time, your main recall/latency dial). Best recall per millisecond, but RAM-heavy and slow to build.
  • IVF (inverted file): k-means splits the vectors into nlist clusters; a query scans only the nprobe closest. Cheaper to build; misses neighbors sitting across a cluster border.
  • PQ (product quantization): chops each vector into sub-vectors and stores a 1-byte centroid code for each, 32–64× smaller. Distances become approximate, so it usually ships as IVF-PQ plus rescoring with full vectors.
  • DiskANN: a graph on SSD with compressed vectors in RAM; billion-scale on one machine.

Every knob moves you along the same curve: more recall costs latency or memory.

Code Sweep efSearch and nprobe against brute-force ground truth
pythonSweep efSearch and nprobe against brute-force ground truth
import faiss
import numpy as np

xb = np.load("doc_embeddings.npy").astype("float32")    # (N, d) real embeddings
xq = np.load("query_embeddings.npy").astype("float32")  # (Q, d) real queries
faiss.normalize_L2(xb); faiss.normalize_L2(xq)          # unit vectors: L2 order = cosine order
d, k = xb.shape[1], 10

exact = faiss.IndexFlatL2(d)       # brute force, O(N·d) per query: the ground truth
exact.add(xb)
_, truth = exact.search(xq, k)

def recall(found) -> float:        # share of the true top-k we got back
    return np.mean([len(set(f) & set(t)) / k for f, t in zip(found, truth)])

hnsw = faiss.IndexHNSWFlat(d, 32)  # M = 32 links per node: more RAM, better recall
hnsw.hnsw.efConstruction = 200     # build effort, paid once
hnsw.add(xb)
for ef in (16, 64, 256):           # efSearch: the query-time recall/latency dial
    hnsw.hnsw.efSearch = ef
    print("HNSW efSearch", ef, recall(hnsw.search(xq, k)[1]))

quantizer = faiss.IndexFlatL2(d)
# 1,024 clusters, 1 byte per 16 dims (d must be divisible by 16)
ivfpq = faiss.IndexIVFPQ(quantizer, d, 1024, d // 16, 8)
ivfpq.train(xb)                    # k-means centroids + PQ codebooks
ivfpq.add(xb)
for nprobe in (1, 16, 64):         # clusters scanned per query
    ivfpq.nprobe = nprobe          # expect lower recall: rescore a top 100 in production
    print("IVF-PQ nprobe", nprobe, recall(ivfpq.search(xq, k)[1]))
Real example

A docs-search team has 10M chunks × 768 dims. Brute force reads ~31 GB per query, roughly 0.1–1 s on a CPU server, bound by memory bandwidth. HNSW (M = 32) needs ~31 GB of vectors plus ~2.6 GB of links, so they rent a 64 GB node, sweep efSearch on 1,000 real queries against brute-force ground truth, and keep the smallest value with recall@10 ≥ 0.95. A 1B-vector image corpus would need ~3 TB of RAM that way; there they use IVF-PQ at 48 bytes per vector (~48 GB of codes) and rescore the top 100 with full vectors.

Trade-offs +3 · −3

+ You gain

  • Millisecond queries over millions of vectors instead of a full scan.
  • A per-query dial (efSearch, nprobe) lets you buy recall with latency.
  • PQ and quantization cut memory 4–64×, which makes billion-scale affordable.

− You pay

  • Approximate: some true neighbors are silently missed, so recall must be measured.
  • HNSW is RAM-hungry and slow to build; deletes leave tombstones that degrade the graph.
  • IVF and PQ must be trained on representative data and lose recall when the data drifts.

Use it when

Beyond ~100k–1M vectors, or when p95 must stay under ~10–20 ms. HNSW by default; IVF-PQ or DiskANN when the vectors do not fit in RAM or cost per vector dominates.

Avoid it when

Small corpora (under ~100k vectors) or when results must be exact, as in dedup audits or compliance lookups: brute force on CPU or GPU is simpler and fast enough.

Numbers to know 5
  • Exact kNN over 10M × 768 float32 reads ~31 GB per query.
  • Common HNSW starting points: M = 16, efConstruction = 64–200, efSearch = 40–100 (and always ≥ k).
  • PQ at 1 byte per 16 dims: a 1536-dim float32 vector goes from 6 KB to 96 bytes (64×).
  • pgvector IVFFlat guidance: lists = rows/1000 up to 1M rows, √rows above; probes ≈ √lists.
  • DiskANN paper: a billion-point index on one workstation with 64 GB of RAM plus an SSD.
Common pitfalls 4
  • Never measuring recall@k on your own queries: results on SIFT or random vectors do not transfer to your embeddings.
  • efSearch below k, or nprobe = 1, and then blaming the embedding model for bad retrieval.
  • Training IVF/PQ on a small or stale sample, then adding very different data: clusters become unbalanced.
  • Heavy deletes on HNSW without rebuilds: tombstones waste memory and degrade recall.
Interview questions 2

Answer out loud first, then reveal.

HNSW or IVF-PQ: which would you pick?Show answer

It is a memory question first. If vectors plus graph fit in RAM, I pick HNSW: the best recall-per-millisecond curve, no training step, incremental inserts. If they do not, or cost per vector dominates, IVF-PQ compresses 32–64× at a recall cost, so I over-fetch ~100 candidates and rescore them with full-precision vectors. At billions of vectors with fast SSDs, DiskANN. Either way I set efSearch or nprobe from a measured recall@10 versus p95 curve on our real queries, not from defaults.

Retrieval got worse after the corpus grew 10×. What happened?Show answer

Most likely the ANN parameters were tuned for the old size. With HNSW, the same efSearch explores a smaller share of a bigger graph, and accumulated deletes leave tombstones. With IVF, centroids trained on the old data become unbalanced, so a fixed nprobe covers less. I would measure recall@10 against brute force on a sample of real queries, re-tune efSearch or nprobe, and schedule rebuilds or retraining. I would also check filters: a selective filter on a bigger index starves the candidate list.