HNSW Indexes
Hierarchical navigable small-world graphs for fast approximate nearest neighbor search.
In plain words
The index is a network of connections between similar items; to find a match, you hop from item to item, always towards the question.
Think of it like…
Finding a house in an unfamiliar country: first use a map of motorways to get to the right region, then main roads to the right city, then local streets to the exact address. Each step zooms in, so you never check every house.
Where you’ve seen it
A team indexes 20 million 1,024-dimension vectors. With M = 16 and efSearch = 40, queries take 3 ms at 91 percent recall@10. Raising efSearch to 120 costs 8 ms and reaches 98 percent. Raising M to 32 and rebuilding improves recall at the same efSearch but increases index size by about 30 percent and build time by 2×. They choose M = 16, efSearch = 100 as the cheapest setting that meets their 97 percent target.
Words you’ll hear
- M
- Maximum links per node per layer (layer 0 allows about 2M); higher improves recall and raises memory and build time.
- efConstruction
- How many candidates are explored when inserting a node; higher builds a better graph but slows indexing.
- efSearch
- How many candidates are explored per query; must be at least k; higher raises recall and latency.
- Recall@k
- Fraction of the true k nearest neighbours the index returns.
Visual diagram
Theory & deep dive
How build and search work
When a vector is inserted, it's assigned a random maximum layer (exponentially fewer nodes reach higher layers). Starting from the top entry point, the algorithm greedily descends to that layer, then at each layer from there down it finds the efConstruction nearest candidates and connects the new node to up to M of them, pruning links with a heuristic that keeps diverse directions. This yields a "navigable small world": any node can be reached from any other in few hops.
A query descends greedily through the upper layers using a single best candidate, then at layer 0 runs a best-first search keeping a priority queue of size efSearch, expanding the closest unvisited node each step until no candidate improves the result. Cost grows roughly logarithmically with the number of vectors, which is why 100 million vectors can still answer in tens of milliseconds, provided the graph and vectors are in memory (random access over disk is slow).
20M vectors × 1,024 dims × 4 bytes ≈ 82 GB for vectors. With M = 16, layer-0 links ≈ 32 × 4 bytes ≈ 128 bytes per node, about 2.6 GB more, so the graph is small relative to the vectors; M = 64 would add roughly 10 GB.
Tuning, filters and limits
Tune empirically: build one index with reasonable settings (M 16 to 32, efConstruction 100 to 200), then sweep efSearch and plot recall@k against latency using a sample of real queries and exact search as ground truth; pick the smallest efSearch that meets your recall target with headroom for growth. Increase M or efConstruction only if recall plateaus below target. Keep efSearch ≥ k, and for reranking pipelines retrieve more candidates (k = 50 to 100) cheaply and rerank them.
Weak spots: heavily filtered queries (the graph is built over all vectors, so a selective filter leaves disconnected regions and can lower recall; engines mitigate this with filter-aware traversal, extra links or iterative scans), deletes and updates (tombstones accumulate and need compaction or rebuild), build time (single-threaded insertion is slow, so use parallel builds and bulk loading) and memory (the index should be resident in RAM). Quantisation (scalar, product or binary) shrinks vectors and speeds search at some recall cost, and disk-based variants (DiskANN, Vamana) serve datasets larger than RAM.
efSearch 20 → recall 0.86, 2 ms; 50 → 0.94, 4 ms; 100 → 0.975, 7 ms; 200 → 0.99, 13 ms. If the target is 0.97, choose 100, then re-run the sweep after the corpus doubles.
How it works, step by step
Step 1 of 41. Build ground truth
Take 200–1,000 real queries and compute exact nearest neighbours by brute force to measure recall against.
- Sample
- real queries
When to use it & trade-offs
What it is
HNSW (Hierarchical Navigable Small World) is the most widely used index for approximate nearest-neighbour search. It builds a layered graph: each vector is a node linked to a few nearby nodes, the sparse top layers act like express lanes that jump across the space, and the dense bottom layer holds every vector. A query enters at the top, greedily moves to whichever neighbour is closer to the query, drops a layer, and repeats, examining only a few hundred nodes out of millions. Three knobs matter: M (links per node), efConstruction (build-time search width) and efSearch (query-time search width).
Why it matters: HNSW is the default in pgvector, Qdrant, Weaviate, OpenSearch, Milvus and others because it delivers high recall at millisecond latency without a training step. But its memory use, build time and recall behaviour under filters surprise teams that treat it as a black box. Understanding the knobs lets you hit a recall target at minimum cost and explain regressions.
When to reach for it
- Low-latency semantic search over millions of vectors
- RAG retrieval with a reranker behind it
- Systems that need incremental inserts
When to avoid or be careful
- Setting efSearch below k
- Judging recall without exact ground truth
- Letting the index spill out of RAM and expecting the same latency
ANN index families
Strengths: Excellent recall-speed trade-off; incremental inserts.
Watch out: RAM-hungry; slow builds; deletes are awkward.
Strengths: Smaller; quantisation shrinks vectors.
Watch out: Needs training; lower recall at the same speed.
Strengths: SSD-resident; high recall.
Watch out: More complex; higher latency than in-memory.
Interview signals & numbers to know
When this topic comes up
- “How does HNSW work?”
- “Recall dropped after we added filters”
- “Build is slow / index is big”
- efSearch tuning
- Approximate vs exact search
Benchmarks & rules of thumb
- 16 – 32
- typical M
- O(log N)
- approximate search cost growth
- ≥ k
- minimum efSearch
Common mistakes & follow-ups
Common interview mistakes
- Tuning efSearch by eye on three queries and shipping 85 percent recall.
- Raising M to fix recall when the real cause was a selective filter.
- Deleting millions of rows and never compacting, so searches wade through tombstones.
Likely interviewer follow-ups
- Walk me through an HNSW search.
- What do M, efConstruction and efSearch control?
- Why can filters hurt recall in HNSW?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply HNSW Indexes with generative AI interview Q&A and hands-on practice.