SDE & MLE Prep

Vector Search & ANN Indexes

Q: How do vector databases find nearest neighbours among a billion embeddings?

Exact search is O(N·d) per query — too slow at scale, so we trade a little recall for speed with approximate nearest neighbour (ANN) indexes:

IndexIdeaTrade-offs
HNSWmulti-layer proximity graph; greedy search from a sparse top layer down to a dense bottom layerexcellent recall/latency; memory heavy (vectors + graph); slow-ish inserts; the common default
IVFk-means "coarse" clusters; search only the nprobe closest clustersfast, tunable; recall drops if neighbours sit in unprobed clusters
PQ (product quantization)split each vector into m sub-vectors, replace each by one of 256 centroids → m bytes per vector10–100× compression; approximate distances; combine as IVF-PQ for billions of vectors
DiskANN / ScaNNgraph on SSD / anisotropic quantizationbillion scale on one machine; high throughput
  • Knobs: efSearch (HNSW) and nprobe (IVF) trade recall for latency; measure recall@k against exact search.
  • Cosine similarity = dot product on L2-normalized vectors — normalize at index and query time.
  • Filtering (tenant, date, ACL): pre-filtering can break graph search; post-filtering can return too few results → filtered-HNSW variants, partitioning by tenant, or over-fetching.
  • Hybrid search: combine BM25 and vector scores (reciprocal rank fusion) — better than either alone for RAG.
  • Updates/deletes: HNSW tombstones and periodic rebuilds; keep the raw vectors elsewhere so indexes can be rebuilt with new parameters or embedding models (re-embedding everything when the model changes!).