How do you search a million points quickly?
HNSW, hierarchical navigable small world, is a graph index: every vector is linked to a few near neighbours, in layers. A search hops from neighbour to neighbour towards the question.
It is the index most vector databases use by default, from Qdrant to pgvector. Its settings decide how big the index is, how long it takes to build and how much it misses.
By the end of this lesson
Note
I can tune an HNSW index to reach a recall target.
Key words
| Word | What it means | Example |
|---|---|---|
| Graph | points joined by links | |
| HNSW | a graph index in layers, sparse at the top | |
| Greedy search | always stepping to the nearer neighbour | |
| m | how many links each point keeps | m = 16 |
| ef_construction | how many candidates are kept while building | |
| ef_search | how many candidates are kept while searching |
The cells students fill in are left blank in this preview.
Starter
Have a go
Starter
4 questionsLayers and a greedy walk
Every point is on layer 0, which links each point to its near neighbours. A few points, chosen by chance, are also on layer 1, fewer still on layer 2, and so on.
A search starts on the top layer and makes greedy steps: to whichever neighbour is nearer the question, until none is. Then it drops a layer and carries on. The top layers make long jumps; layer 0 does the fine work.
A search goes down the layers
flowchart TB
T["Top layer: a few points, long links"] --> M["Middle layer: more points"]
M --> B["Layer 0: every point, short links"]
B --> R["The nearest point found"]Walk a small graph you can read
docker exec tools python3 steps/hnswtoy.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Worked example: 300 points, one question
| Step | What hnswtoy.py printed |
|---|---|
| Points per layer, top down | 9, 29, 81, 300 |
| After layers 3, 2 and 1 | point 262, distance 7.3 |
| After layer 0 | point 30, distance 1.9 |
| Distances worked out | 36 of 300 |
| Found the true nearest | True |
The cells students fill in are left blank in this preview.
Check
Have a go
Check
3 questionsTry it: how many layers?
# A point reaches layer 1 with chance 1 in 4, layer 2 with 1 in 16, and so on.
points = 1000000
chance = 4
layer = 0
left = points
while left >= 1:
print("layer", layer, "about", left, "points")
left = left // chance
layer = layer + 1
# Change chance to 16, as a bigger m would. How many layers are left?
Make a free account to save your work and track your progress.
m and ef_construction shape the graph
m is how many links each point keeps; layer 0 keeps twice as many. More links find more neighbours, but the index grows and takes longer to build.
ef_construction is how many candidates the build keeps while choosing each point's links. More gives better links and a slower build. In pgvector the defaults are m 16 and ef_construction 64. Qdrant's are m 16 and ef_construct 100.
Build an HNSW index in pgvector
docker exec pg psql -U lab -d shop -c "CREATE INDEX docs_hnsw ON docs USING hnsw (embedding vector_cosine_ops) WITH (m = 16, ef_construction = 64)"Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Read Qdrant's HNSW settings
curl -s http://qdrant:6333/collections/docsShown here, not run. Press Start lab to type it into your own lab’s terminal.
Check
Have a go
Check
3 questionsef_search is the dial at query time
A real search keeps a list of the best ef_search candidates on layer 0, not just one point. A longer list finds more true neighbours and takes longer.
pgvector calls it hnsw.ef_search, 40 by default, and you set it for a session. Qdrant calls it hnsw_ef and takes it with each search. Measure recall at a few values and keep the smallest that meets your target.
Recall with hnsw.ef_search at 10
docker exec tools python3 steps/pgrecall.py hnsw 10Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Recall with hnsw.ef_search at 40
docker exec tools python3 steps/pgrecall.py hnsw 40Shown here, not run. Press Start lab to type it into your own lab’s terminal.
A common mistake
Warning
Many people think LIMIT 100 always returns 100 rows from an HNSW index. pgvector's HNSW scan returns at most hnsw.ef_search rows, 40 by default. Set ef_search at least as large as the LIMIT, as the next two Runs show.
Ask for 100 rows
docker exec pg psql -U lab -d shop -c "SELECT count(*) FROM (SELECT id FROM docs ORDER BY embedding <=> (SELECT embedding FROM questions WHERE id = 1) LIMIT 100) AS found"Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Ask for 100 rows with ef_search 100
docker exec pg psql -U lab -d shop -c "SET hnsw.ef_search = 100" -c "SELECT count(*) FROM (SELECT id FROM docs ORDER BY embedding <=> (SELECT embedding FROM questions WHERE id = 1) LIMIT 100) AS found"Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Check
Have a go
Check
3 questionsAssignment: search a layered graph
Points are a dictionary from an id to [x, y]. A graph layer is a dictionary from an id to the list of its neighbours' ids. Write three functions.
distance(a, b) is the straight-line distance between two points. greedy(graph, points, start, question) walks one layer: from start, move to the neighbour nearest the question if it is nearer than where you are, and repeat until no neighbour is nearer. If two neighbours are equally near, take the one listed first. Return the list of ids visited, start first. layered(layers, points, entry, question) runs greedy on each layer from the top layer (the first in the list) to layer 0, each starting where the last one stopped, and returns the id it ends on.
def distance(a, b):
return 0
def greedy(graph, points, start, question):
return [start]
def layered(layers, points, entry, question):
return entry
Make a free account to save your work and track your progress.
Exit quiz
Have a go