Lesson 22.2 · 2 of 8 · 5 min read · Reviewed 24 Nov 2026
HNSW graphs
By the end, you can
- Explain how an HNSW index finds nearest neighbours.
- Tune its main settings.
HNSWHNSW: Hierarchical navigable small world: a graph-based index for fast approximate nearest neighbour search. stands for Hierarchical Navigable Small World graphs. It’s the most widely used ANNApproximate nearest neighbour (ANN): Search that finds vectors close to a query very quickly by accepting that it may occasionally miss the exact nearest one. index in vector databasesVector database: A database built to store embeddings and find the nearest ones to a query quickly..
The structure
layer 2: A ------------------------- F (few nodes, long links)
| |
layer 1: A ------- C ------- E ----- F (more nodes)
| | | |
layer 0: A - B - C - D - E - F - G - H - ... (every node, short links)
Each vector is a node. Every node is in layer 0; a random few also appear in higher layers.
Searching
- Start at an entry node in the top layer.
- Move to whichever neighbour is closest to the query; repeat until no neighbour is closer.
- Drop to the next layer and repeat from there.
- In layer 0, keep a candidate list of size ef and explore around it.
- Return the best k.
Upper layers make big jumps across the space; lower layers refine. It’s like flying to the right city, driving to the street, then walking to the door.
Settings
| Setting | When set | Effect |
|---|---|---|
| M (links per node) | Build | Higher: better recall, more memory |
| efConstruction | Build | Higher: better graph, slower build |
| ef (search) | Query | Higher: better recall, slower query |
Trade-offs
HNSW gives fast, high-recall search but keeps the full graph in memory, and deletes can be awkward. For very large collections, it’s often combined with compression (22.3).
Key points
- HNSW builds layered graphs: sparse upper layers for long jumps, a dense bottom layer for fine search.
- A query starts at the top, greedily moves toward closer nodes, and descends layer by layer.
- Settings like M (links per node) and ef (search breadth) trade memory and speed for recall.
Walk a neighbour graph greedily
Build a small neighbour graph and search it greedily with a candidate list of size ef, the core move inside HNSW.
You will have: A graph search function and a table of recall@5 and distance computations for ef = 1, 4 and 16.
Steps
- Read the setup: 400 random points on a 2D map, each linked to its M = 6 nearest neighbours.
- Write search(): start at node 0, keep the ef closest nodes seen, expand the closest unexpanded one, stop when none is left.
- Return the best 5 and count how many distance computations you made.
- Compare recall@5 with exact search for ef = 1, 4 and 16.
Done when
- ef = 1 behaves like a pure greedy walk and has the lowest recall.
- ef = 16 reaches recall@5 of at least 0.9.
- Distance computations grow with ef.
Open in the Playground No API key needed.
Starter code (Python)
import heapq, math, random
rng = random.Random(7)
PTS = [(rng.random() * 10, rng.random() * 10) for _ in range(400)]
M = 6
def dist(a, b):
return math.dist(a, b)
GRAPH = {i: sorted(range(len(PTS)), key=lambda j: dist(PTS[i], PTS[j]))[1:M + 1] for i in range(len(PTS))}
QUERIES = [(rng.random() * 10, rng.random() * 10) for _ in range(15)]
def search(q, ef, k=5, entry=0):
computed = 0
# TODO: candidates = min-heap of (distance, node) to expand; best = the ef closest seen so far
# TODO: pop the closest candidate; stop if it is further than the worst of best and best is full
# TODO: for each neighbour not yet seen, compute its distance (computed += 1) and push it
return [entry], computed
for ef in (1, 4, 16):
hits, work = 0, 0
for q in QUERIES:
truth = set(sorted(range(len(PTS)), key=lambda j: dist(q, PTS[j]))[:5])
got, c = search(q, ef)
hits += len(truth & set(got)); work += c
print(f"ef={ef}: recall@5 = {hits / (5 * len(QUERIES)):.2f}, distance computations = {work // len(QUERIES)}")
Show a solution
import heapq, math, random
rng = random.Random(7)
PTS = [(rng.random() * 10, rng.random() * 10) for _ in range(400)]
M = 6
def dist(a, b):
return math.dist(a, b)
GRAPH = {i: sorted(range(len(PTS)), key=lambda j: dist(PTS[i], PTS[j]))[1:M + 1] for i in range(len(PTS))}
# Add the reverse links so the graph is navigable in both directions.
for i in list(GRAPH):
for j in list(GRAPH[i]):
if i not in GRAPH[j]:
GRAPH[j].append(i)
QUERIES = [(rng.random() * 10, rng.random() * 10) for _ in range(15)]
def search(q, ef, k=5, entry=0):
d0 = dist(q, PTS[entry]); computed = 1
seen = {entry}
candidates = [(d0, entry)] # min-heap: closest first
best = [(-d0, entry)] # max-heap of the ef closest found
while candidates:
d, node = heapq.heappop(candidates)
if len(best) >= ef and d > -best[0][0]:
break
for nb in GRAPH[node]:
if nb in seen:
continue
seen.add(nb)
dn = dist(q, PTS[nb]); computed += 1
if len(best) < ef or dn < -best[0][0]:
heapq.heappush(candidates, (dn, nb))
heapq.heappush(best, (-dn, nb))
if len(best) > ef:
heapq.heappop(best)
ranked = sorted((-negd, n) for negd, n in best)
return [n for _, n in ranked[:k]], computed
results = []
for ef in (1, 4, 16):
hits, work = 0, 0
for q in QUERIES:
truth = set(sorted(range(len(PTS)), key=lambda j: dist(q, PTS[j]))[:5])
got, c = search(q, ef)
hits += len(truth & set(got)); work += c
results.append((hits / (5 * len(QUERIES)), work // len(QUERIES)))
print(f"ef={ef}: recall@5 = {results[-1][0]:.2f}, distance computations = {results[-1][1]}")
print("more ef, more work:", results[0][1] < results[1][1] < results[2][1])
print("ef=16 recall at least 0.9:", results[2][0] >= 0.9)