Vector Search & ANN Indexes
HNSW, IVF, and product quantization — how approximate nearest neighbour search trades a little recall for a thousand-fold speedup, and the filtering problem nobody mentions.
#Why exact search doesn't work
Finding the nearest vectors to a query is trivially correct by brute force: compute the distance to every vector, keep the top k.
The escape is to give up exactness. Approximate nearest neighbour search returns most of the true nearest neighbours — 95–99% — for a 100–1,000× speedup. Since embeddings are themselves approximate representations of meaning, missing the 9th-best of 10 results is usually invisible.
Recall@k is the metric: of the true top-k, how many did we return? Recall 0.95 at k=10 means we found 9.5 of the true 10 on average.
#HNSW
The dominant algorithm, and its name describes it: hierarchical navigable small world. Connect each vector to its nearest neighbours so the whole collection becomes a graph you can walk, then keep stepping toward whichever neighbour is closest to your query.
The "hierarchical" part is the trick. Build several layers — a sparse top layer with long-range links for covering ground quickly, denser layers below for precision — so a search zooms in rather than crawling. It's the same idea as a skip list, in many dimensions.
HIERARCHICAL NAVIGABLE SMALL WORLD
Layer 2 ●──────────────● few nodes, long links
│ │ (coarse navigation)
Layer 1 ●────●────●────●────● more nodes, medium links
│ │ │ │ │
Layer 0 ●─●─●─●─●─●─●─●─●─●─● ALL nodes, short links
(fine navigation)
SEARCH
1. enter at the top layer
2. greedily move to whichever neighbour is closer
to the query, until no neighbour improves
3. drop to the next layer down, continue from there
4. at layer 0, keep a candidate list of size ef
and return the best k
Each layer roughly halves the remaining distance,
giving O(log N) hops instead of O(N) comparisons.The structure is a skip list generalised to metric space: sparse upper layers for fast coarse movement, a dense bottom layer for precision.
| Parameter | Effect | Typical |
|---|---|---|
| M | Links per node. Higher = better recall, more memory | 16–64 |
| ef_construction | Candidate list size while building. Higher = better graph, slower build | 100–500 |
| ef_search | Candidate list size at query time. The runtime recall/latency dial | 50–500 |
HNSW's weaknesses, which matter in practice: memory is high (the graph is roughly M × 2 × 4 bytes per node on top of the vectors); build time is long; and deletion is awkward. You can't simply cut a node out, because other nodes' search paths run through it. Instead you tombstone it — mark it "deleted, skip in results" while leaving it in the graph — and as tombstones pile up, searches waste hops on dead nodes and recall slowly degrades until you rebuild.
#IVF and product quantization
The other major family, and the one that scales to memory-constrained deployments.
IVF (inverted file) — partition, then search a few partitions
Build: k-means the vectors into nlist clusters (e.g. 4,096)
store each vector in its cluster's list
Query: find the nprobe nearest centroids
search only those lists exhaustively
nlist = 4,096, nprobe = 32
→ search 32/4,096 = 0.8% of the data
→ ~128× speedup, some recall loss when the true
neighbour sits in an unprobed clusterProduct quantization compresses the vectors themselves, and it's what makes billion-scale indexes fit in memory. The idea: chop each vector into short pieces, and for each piece keep only "which of these 256 standard pieces does it most resemble?" — one byte instead of thirty-two. You lose the exact values and keep enough to rank by.
IVF-PQ is the standard combination: partition with IVF, compress with PQ, and optionally re-rank the top candidates with full-precision vectors to recover most of the lost recall.
RaBitQ (Gao & Long, SIGMOD 2024) is the newer quantizer worth knowing. It applies a random rotation to each vector, then keeps about one bit per dimension — the same 32× saving as the PQ example — but with a proven bound on how wrong each distance estimate can be. That bound lets the search decide, candidate by candidate, whether the cheap estimate is good enough or the full vector has to be fetched, which gives PQ-level memory with steadier recall. Extended versions spend a few more bits per dimension for accuracy, and several vector databases adopted it in 2024–25.
#Choosing an index
| Index | Memory | Build | Query | Recall | Best for |
|---|---|---|---|---|---|
| Flat (brute force) | 1× vectors | None | Slow | 1.00 | <1M vectors, or a re-ranking stage |
| HNSW | 1.5–2× | Slow | Very fast | 0.95–0.99 | The default up to ~100M in RAM |
| IVF-Flat | ~1× | Medium | Fast | 0.90–0.98 | Large, memory available |
| IVF-PQ | 0.03–0.1× | Medium | Fast | 0.85–0.95 | Billion-scale, memory-constrained |
| ScaNN | ~0.2× | Medium | Very fast | 0.93–0.98 | Anisotropic quantization; strong on MIPS (dot-product search, see below) |
| DiskANN | Small RAM + SSD | Slow | Medium | 0.94–0.98 | Billion-scale on one machine |
DiskANN deserves a mention because it changes the cost structure: keep compressed vectors in RAM for navigation and the full graph on SSD, fetching only the nodes actually visited. A billion vectors on one machine with a few hundred gigabytes of SSD — a completely different infrastructure bill from a distributed in-memory index.
Vector indexes on object storage are the newest point on that curve. Amazon S3 Vectors (generally available December 2025, up to 2 billion vectors per index) stores and searches vectors directly in object storage: queries take around 100 ms on frequently used indexes and up to about a second otherwise, at a small fraction of the cost of keeping vectors in RAM. That suits large corpora queried occasionally — archives, long-term agent memory. Hot, latency-critical search still belongs in memory, and a common design tiers between the two.
#The filtering problem
The part that breaks most naive designs. Real queries aren't "find similar documents" — they're "find similar documents that this user can access, in English, from the last 90 days."
PRE-FILTER — filter first, then search
apply the predicate, then brute-force the survivors
✓ exact, correct
✗ if 2% survive, that's still 2M vectors to scan
✗ the ANN index is useless — the graph's links run
through filtered-out nodes too, so you can't walk
it using only the survivors
POST-FILTER — search first, then filter
get top 1,000 by similarity, drop those failing the predicate
✓ uses the index normally
✗ if the predicate is selective (0.1% match), you may
get ZERO results back from 1,000 candidates
✗ recall is unpredictable and depends on the predicate
FILTERED SEARCH — evaluate the predicate during traversal
walk the graph, skip nodes failing the predicate,
keep walking
✓ one pass, good recall
✗ the graph can become disconnected under a selective
filter — you get stranded in a region with no
passing neighbours#Distance metrics and one sharp edge
Cosine, dot product, and Euclidean, as in embeddings. For normalised vectors they rank identically.
The edge case: maximum inner product search (MIPS) is not the same problem as nearest neighbour. With unnormalised vectors, the highest dot product may be far away in Euclidean distance — a large-magnitude vector at a wide angle can beat a close one. Graph-based indexes assume the triangle inequality — "if A is near B and B is near C, then A is near C" — because that's what makes walking from neighbour to neighbour lead you toward the answer. Inner product doesn't obey it, so HNSW on unnormalised vectors can walk away from the best result and silently lose recall.
The fixes: normalise and use cosine (usual answer), or use an index built for MIPS (ScaNN). If your recommendation system deliberately encodes popularity in the magnitude — popular items get longer vectors so they score higher — you need the second, because normalising would erase that signal.
#Operations
Building costs real time. HNSW on 100M × 768-dim vectors is hours on a large machine. Plan for it; parallelise across shards; and never make it part of a request path.
Updates are the awkward part. HNSW handles insertion well and deletion badly — tombstones accumulate and recall degrades. The standard pattern is a large immutable base index plus a small in-memory delta index that holds only recent changes. Every query searches both and combines the results, and the delta is merged into a fresh base periodically. Exactly the LSM tree pattern, applied to vectors.
Memory is the binding cost. Compute the full budget — vectors, graph overhead, metadata, and double it for the rebuild window, because the old index keeps serving queries while the new one is built, so both sit in memory at once. That last term is the one people forget until the rebuild runs out of memory and crashes.
#Check yourself
When does brute-force vector search stop working?Show answer
What does approximate nearest-neighbour search trade?Show answer
How does HNSW search?Show answer
Why is ef_search the important HNSW knob?Show answer
How do IVF and product quantization scale to billions?Show answer
What do RaBitQ, DiskANN and object-storage indexes change?Show answer
How do you choose a filtering strategy?Show answer
Name two operational traps in vector search.Show answer
#What to carry forward
- Brute force dies around 1M vectors. ANN trades a few percent recall for 100–1,000×.
- HNSW is the default:
ef_searchis a per-query recall/latency dial, usable for graceful degradation. - IVF-PQ gets 32× compression with lookup-table distances — how billion-scale fits in memory.
- DiskANN moves the graph to SSD, changing the cost structure entirely.
- Filtering strategy is decided by selectivity. Partition the index on your dominant filter where you can.
- MIPS is not NN — normalise, or use an index built for it.
- Budget memory for the rebuild window, when two indexes are live at once.