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

Free lesson

Exact and approximate nearest neighbour search

After this lesson: I can measure the recall of an approximate search against an exact one.

60 min lesson3 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

Is the nearest answer worth the wait?

Approximate nearest neighbour search finds vectors close to a question without comparing it with every vector, and may miss a few. Exact search compares it with all of them and never misses.

With a million vectors, exact search is too slow for a chat window. Every vector database makes this trade, and you choose where it sits.

By the end of this lesson

Note

I can measure the recall of an approximate search against an exact one.

Key words

WordWhat it meansExample
kNNthe k nearest vectors to a question
Exact searchcomparing the question with every vector
ANNapproximate nearest neighbour search, which may miss some
Recall@kthe share of the true top k a search found8 of 10 = 0.8
Latencyhow long one search takes
Indexa structure that avoids comparing every vector

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

Exact search compares with every vector

An exact kNN search works out the distance from the question to every vector, then keeps the k best. It never misses.

Its cost is the number of vectors times their length. The lab's 20,000 vectors of 48 numbers need 960,000 multiply-adds for one question. A million vectors of 768 numbers need 768 million, for every question.

An exact search in plain Python

Command
docker exec tools python3 steps/exact.py

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

The cost of one exact search

VectorsNumbers eachMultiply-adds a question
20,000 (the lab)48960,000
1,000,000768768,000,000
100,000,0001,536153,600,000,000

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: the work of exact search

Code: python
# An exact search does one multiply-add per number of every vector.
vectors = 20000
numbers = 48
questions_a_second = 100
work = vectors * numbers
print("multiply-adds for one question:", work)
print("for", questions_a_second, "questions a second:", work * questions_a_second)
# Try 1,000,000 vectors of 768 numbers. How many times more work is that?

Make a free account to save your work and track your progress.

Recall@k measures what an index missed

An index compares the question with only a small part of the data, so ANN search can miss a true neighbour. You measure how much with recall@k.

Take the exact top 10 as the right answer. Count how many of them the index also returned, and divide by 10. Do it for many questions and take the mean, because one question can be lucky.

Worked example: recall@10 for one question

ListIds returned
Exact top 104, 9, 2, 7, 1, 8, 3, 6, 5, 10
Index top 104, 9, 7, 2, 1, 8, 3, 11, 12, 6
In both4, 9, 2, 7, 1, 8, 3, 6: 8 of 10
Recall@100.8

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

A common mistake

Warning

Many people think an approximate search returns the right items with slightly wrong scores. The scores it returns are exact. What it can do is miss an item altogether, so measure it with recall, not by checking scores.

More effort, more recall, more time

An HNSW index has a search setting, called hnsw_ef in Qdrant: how many candidates it keeps while it searches. A larger value finds more true neighbours and takes longer.

Choose the smallest setting that reaches the recall you need, measured on questions like your users' questions. In the lab the times are tiny because 20,000 vectors is small. The gap grows with the data.

Measure recall at five settings

Command
docker exec tools python3 steps/recall.py

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

What recall.py printed in the lab

SearchRecall@10, aboutTime
Exact1.0The most
hnsw_ef 100.85Less than exact
hnsw_ef 160.92Less than exact
hnsw_ef 320.99Less than exact
hnsw_ef 64 and 1281.0Grows with the setting

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

See PostgreSQL read every row

Command
docker exec pg psql -U lab -d shop -c "EXPLAIN (COSTS OFF) SELECT id FROM docs ORDER BY embedding <=> (SELECT embedding FROM questions WHERE id = 1) LIMIT 10"

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: measure recall and choose

Write three functions for measuring an index.

recall_at_k(exact, found, k) is the share of the first k ids of exact that are among the first k ids of found, as a fraction. mean_recall(pairs, k) takes a list of [exact, found] pairs, one per question, and gives the mean recall@k rounded to 2 places. cheapest(results, target) takes a list of [setting, recall, ms] rows and gives the setting with the smallest ms among those whose recall is at least target. If two rows have the same ms, give the earlier one. If none reaches the target, give None.

Code: python
def recall_at_k(exact, found, k):
    return 0.0


def mean_recall(pairs, k):
    return 0.0


def cheapest(results, target):
    return None

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.