Sub topic 6
HNSW: navigating a layered graph
This chapter assumes you know what embeddings are, how cosine and Euclidean distance work, and why exact search becomes slow at scale. It also assumes you have seen approximate nearest neighbor (ANN) search and recall defined.
The idea
HNSW stands for Hierarchical Navigable Small World. It builds a graph in which each vector is a node. Each node links to a few nearby vectors. To search, you start at an entry point and repeatedly move to whichever neighbor is closer to the query. You stop when no neighbor improves on your current position.
A single flat graph can still need many hops to cross a large dataset. HNSW fixes this by stacking layers:
- Layer 0 holds every vector, with short links between close neighbors.
- Higher layers hold random subsets of the vectors. Each layer is sparser than the one below it.
- Sparse layers give long jumps. Dense layers give fine detail.
When a vector is inserted, it draws a maximum layer at random. Most vectors stay in layer 0 only. A few reach the upper layers. The number of nodes per layer shrinks geometrically, so the number of hops grows roughly with the logarithm of the dataset size.
How a search works
- Start at the global entry point in the top layer.
- In each layer above 0, walk greedily until no neighbor is closer. Then drop down one layer, starting from the node you reached.
- In layer 0, keep a list of the best
efSearchcandidates found so far. Expand the closest unvisited candidate, add its neighbors, and trim the list. - Return the best
kfrom that list.
Layer 0 uses a beam rather than a single path. This is what lets the search escape local minima, which are dead ends where a node looks closest but better answers lie elsewhere.
The three parameters
| Parameter | Used at | Effect of raising it |
|---|---|---|
| `M` | Build | More links per node. Higher recall and more memory. Slower build. |
| `efConstruction` | Build | A wider candidate search when choosing links. Better graph quality and slower build. |
| `efSearch` | Query | A wider beam. Higher recall and higher latency. |
M and efConstruction are fixed once the index is built, so changing them means rebuilding. efSearch can change per query. This makes it the first knob to tune.
Running it
This code compares HNSW with an exact FAISS index and measures recall@10.
import numpy as np
import faiss
d = 64
xb = np.random.default_rng(0).normal(size=(10000, d)).astype("float32")
xq = xb[:100]
k = 10
flat = faiss.IndexFlatL2(d)
flat.add(xb)
_, true_ids = flat.search(xq, k)
hnsw = faiss.IndexHNSWFlat(d, 32)
hnsw.hnsw.efConstruction = 200
hnsw.add(xb)
for ef in (16, 64, 256):
hnsw.hnsw.efSearch = ef
_, ann_ids = hnsw.search(xq, k)
recall = np.mean([len(set(a) & set(t)) / k for a, t in zip(ann_ids, true_ids)])
print(f"efSearch={ef}: recall@{k}={recall:.3f}")Recall should rise as efSearch rises, while each query takes longer.
Common errors
- Setting
efSearchbelowk. The beam cannot returnkresults if it holds fewer thankcandidates. KeepefSearchat least as large ask. - Tuning on too little data. Recall on a small test set can look perfect and then drop at production scale.
- Ignoring memory. HNSW keeps the full vectors and the graph in RAM. The links cost roughly
Mtimes a few bytes per node on top of the vectors. - Changing the metric after the build. The graph is built for one distance function. Use the same metric at query time.
Exercise
Your HNSW index returns 0.82 recall@10 and queries take 3 ms. You need recall above 0.95 and can accept 8 ms. Which parameter do you change first, and why?
Show answer
Raise efSearch. It acts at query time, so you can test it without rebuilding the index, and it trades latency for recall directly. If recall is still too low at an acceptable latency, rebuild with a larger M or efConstruction.