Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

How an HNSW index works

After this lesson: I can tune an HNSW index to reach a recall target.

60 min lesson7 commandsVector database lab: Qdrant and PostgreSQL with pgvector

A quick check that you are not a bot, then your own lab opens on the interactive lesson.

Already have an account? Sign in

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

WordWhat it meansExample
Graphpoints joined by links
HNSWa graph index in layers, sparse at the top
Greedy searchalways stepping to the nearer neighbour
mhow many links each point keepsm = 16
ef_constructionhow many candidates are kept while building
ef_searchhow many candidates are kept while searching

The cells students fill in are left blank in this preview.

Starter

Have a go

Starter

4 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Layers 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

Command
docker exec tools python3 steps/hnswtoy.py

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Worked example: 300 points, one question

StepWhat hnswtoy.py printed
Points per layer, top down9, 29, 81, 300
After layers 3, 2 and 1point 262, distance 7.3
After layer 0point 30, distance 1.9
Distances worked out36 of 300
Found the true nearestTrue

The cells students fill in are left blank in this preview.

Check

Have a go

Check

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Try it: how many layers?

Code: python
# 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

Command
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

Command
curl -s http://qdrant:6333/collections/docs

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Check

Have a go

Check

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

ef_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

Command
docker exec tools python3 steps/pgrecall.py hnsw 10

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Recall with hnsw.ef_search at 40

Command
docker exec tools python3 steps/pgrecall.py hnsw 40

Shown 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

Command
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

Command
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 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Assignment: 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.

Code: python
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

Exit quiz

5 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Teaching a class? Set this module for your students with a teacher guide, marked assignments and a lab for every student.