Sub topic 6
HNSW: Navigating a Layered Graph
This chapter assumes you know what an embedding is, how cosine and Euclidean distance work, and why exact search becomes too slow at scale. You should also know what recall means for an approximate index. You should be able to read short Python and SQL.
The idea behind HNSW
HNSW stands for Hierarchical Navigable Small World. It is a graph index. Each vector is a node, and each node stores links to a few nearby nodes. To answer a query, the search starts at some node and repeatedly moves to whichever linked node is closer to the query. It stops when no neighbor is closer.
This greedy walk is fast because a "small world" graph has short paths between any two nodes. It would still get stuck easily on a flat graph with only local links, and it would take many hops to cross the space. HNSW fixes both problems with layers.
The layered structure
HNSW builds several graphs stacked on top of each other.
- Layer 0 contains every vector. Its links connect close neighbors.
- Higher layers contain progressively fewer vectors, chosen at random.
- Each vector appears in layer 0 and in every layer up to its own randomly assigned top layer.
- The top layer holds only a handful of nodes and acts as a coarse map.
The top layer for each new vector is drawn from an exponentially decaying distribution. Roughly, a fixed fraction of the nodes on one layer also appear on the layer above. This gives a skip-list-like structure. Upper layers have long-range links that cover big distances in a few hops. Lower layers have short links that refine the position.
How a search works
A search has two phases.
- Descent. Start at the global entry point in the top layer. In each layer above 0, do a greedy walk: move to the neighbor closest to the query until no neighbor improves. Use the node you stop at as the entry point for the next layer down.
- Layer 0 search. Keep a candidate list of size
ef(calledefSearchin FAISS andef_searchin pgvector). Repeatedly take the closest unvisited candidate, look at its neighbors, and add any that are closer than the worst current candidate. Stop when the nearest unvisited candidate is farther than the worst entry in the list. Return the bestkfrom the list.
The value ef must be at least k. A larger ef explores more of the graph, which raises recall and latency together. With ef = 1 the layer 0 search is the same greedy walk used in the upper layers, and it often ends in a local minimum, which means a node that looks closest but is not the true nearest neighbor.
How an index is built
Insertion uses the same machinery as search.
- Draw a random top layer
Lfor the new vector. - Descend greedily from the entry point down to layer
L + 1. - At each layer from
Ldown to 0, run a search withefConstructioncandidates to find nearby nodes. - Connect the new node to up to
Mof them, using a heuristic that prefers a diverse set of neighbors over simply the closest ones. - Add the reverse links. If an existing neighbor now has too many links, prune it back to the limit.
The diversity heuristic matters. It skips a candidate if that candidate is closer to an already chosen neighbor than to the new node. Without it, a node in a dense cluster links only to other nodes in the same cluster, and the graph loses the bridges between clusters that make navigation work.
The three parameters
| Parameter | Set at | Effect when raised | Cost |
|---|---|---|---|
| `M` | Build time | Denser graph, better recall, especially on hard data | More memory, slower build, slower search |
| `efConstruction` | Build time | Better graph quality | Slower build, with no effect on index size |
| `efSearch` | Query time | Higher recall | Higher latency |
Some practical points:
Mis the maximum number of links per node in the upper layers. Layer 0 usually allows2 * M. Typical values are 16 to 64.- Memory per vector is roughly the vector itself plus about
2 * Mlinks of 4 bytes each in layer 0. For 768-dimensional float32 vectors, the raw vector takes 3,072 bytes and the links withM = 32take about 256 bytes. The graph is a modest overhead, but the full vectors must stay in memory for fast search. efConstructionis paid once. Choosing a value several times larger thanM, such as 100 to 400, is common.efSearchis the knob you adjust in production, because it changes without rebuilding.
Running HNSW and measuring recall
The following code builds an exact index and an HNSW index over the same data. It then compares them with 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)
hnsw.hnsw.efSearch = 64
_, 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"recall@{k}: {recall:.3f}")The exact index defines the ground truth. Recall@10 is the average fraction of the true ten neighbors that HNSW also returned. To see the trade-off, set hnsw.hnsw.efSearch to 10, 32, 64 and 256, rerun the search, and time each run. Recall climbs with ef and then flattens, while latency keeps growing.
Two cautions about this test. The queries are the first 100 stored vectors, so each query has itself as its nearest neighbor at distance 0. That makes the test easier than real traffic, where queries are not in the index. Random Gaussian data is also unusually hard for graph indexes, because it has no cluster structure, so real embeddings often give better recall at the same settings. Use held-out queries from your own data before you trust any number.
HNSW in a database
Many databases expose HNSW through an index definition. With pgvector, the same three parameters appear as SQL options.
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE items (
id bigserial PRIMARY KEY,
category text,
embedding vector(3)
);
INSERT INTO items (category, embedding) VALUES
('a', '[1, 0, 0]'),
('b', '[0, 1, 0]'),
('a', '[0.9, 0.1, 0]');
CREATE INDEX ON items USING hnsw (embedding vector_cosine_ops)
WITH (m = 16, ef_construction = 64);
SET hnsw.ef_search = 40;
SELECT id, embedding <=> '[1, 0, 0]' AS cosine_distance
FROM items
WHERE category = 'a'
ORDER BY embedding <=> '[1, 0, 0]'
LIMIT 2;The operator class vector_cosine_ops must match the operator in the query. An index built for cosine distance is not used for a query written with <->, which is Euclidean distance. The planner then falls back to a sequential scan, and the query is exact but slow.
Failure modes and gotchas
- Filters applied after the index search. In the query above, the index returns its
ef_searchnearest candidates first, and theWHEREclause removes rows afterward. If few candidates matchcategory = 'a', the query can return fewer rows thanLIMITasks for, or none. Raisingef_search, using a partial index, or using a system with filter-aware traversal reduces this problem. The metadata filtering chapter covers it in detail. - Memory pressure. If the graph and vectors do not fit in RAM, each hop can trigger a disk read, and latency rises sharply. Plan capacity from the memory formula above, and consider compression if the vectors are too large.
- Slow builds. Inserting millions of vectors with a high
efConstructiontakes a long time. Building after loading the data is usually faster than building a large index and then inserting row by row. - Deletes. Removing a node can break paths that other nodes relied on. Many implementations mark nodes as deleted and skip them during search, and a rebuild eventually reclaims the space. Heavy delete workloads degrade quality over time.
- Insertion order effects. Because layer assignment is random and links depend on what is already present, two builds of the same data can differ slightly in recall.
- Not a guarantee. HNSW has no worst-case bound on recall. Test on your own data, including the hardest queries.
When HNSW is a good choice
HNSW is a strong default when you need low latency and high recall, the dataset fits in memory, and updates arrive gradually. It tends to lose to IVF-based indexes when memory is the main constraint, because IVF combined with compression stores far less per vector. It also has a high build cost compared with IVF, which only needs a clustering step.
Exercise
A query against an HNSW index returns recall@10 of 0.82, and latency is well within budget. Which parameter should you change first, and why? What would you change if raising it to a very large value still did not reach the target?
Show answer
Raise efSearch first. It is a query-time parameter, so no rebuild is needed, and it increases the number of candidates explored in layer 0, which raises recall at the cost of latency. If a very large efSearch still falls short, the graph itself is too sparse or poorly connected, so rebuild with a larger M and a larger efConstruction.
Exercise
Explain why the upper layers of an HNSW index make search faster than a walk on layer 0 alone.
Show answer
The upper layers contain few nodes with long-range links, so the greedy walk covers large distances in a few hops and reaches the right region of the space. The search then enters layer 0 close to the query and only needs to explore a small neighborhood, instead of crossing the whole graph through short local links.