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:
| Index | Idea | Trade-offs |
|---|---|---|
| HNSW | multi-layer proximity graph; greedy search from a sparse top layer down to a dense bottom layer | excellent recall/latency; memory heavy (vectors + graph); slow-ish inserts; the common default |
| IVF | k-means "coarse" clusters; search only the nprobe closest clusters | fast, 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 vector | 10–100× compression; approximate distances; combine as IVF-PQ for billions of vectors |
| DiskANN / ScaNN | graph on SSD / anisotropic quantization | billion scale on one machine; high throughput |
- Knobs:
efSearch(HNSW) andnprobe(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!).