Skip to content
AgenticAIWiki
  1. Learn
  2. Part 4
  3. 22. Vector database internals
  4. 22.1

Lesson 22.1 · 1 of 8 · 4 min read · Reviewed 24 Nov 2026

Exact vs approximate nearest neighbour search

By the end, you can

  • Compare exact and approximate nearest neighbour search.
  • Explain the speed and recall trade-off.

Compare the query vector with every stored vector, keep the top k. Simple and perfectly accurate.

cost per query  ~  number of vectors x dimensions
1 million x 1,024 dims  = about a billion multiply-adds

Fine for thousands or a few million vectors, especially on a GPU. Too slow for hundreds of millions at low latencyLatency: The time from sending a request until you get the response, or until the first token arrives when streaming..

Approximate search (ANN)

Build an index that narrows the search to likely candidates. Common families:

Family Idea Chapter
Graph (HNSW) Walk a graph of near neighbours toward the query 22.2
Clustering (IVF) Search only the clusters nearest the query 22.3
Compression (PQ) Store compact codes; compare approximately 22.3

Recall

recall@10 = (true top-10 neighbours found) / 10

An index at 0.95 recall@10 returns, on average, 9.5 of the true top 10. Indexes have settings that raise recall at the cost of speed and memory. Measure recall on your own data by comparing with exact search on a sample.

Does small recall loss matter for RAG?

Often not much: the chunks ranked 9th and 11th are usually similar in usefulness, and rerankingReranking: Re-scoring an initial set of retrieved results with a more accurate model to put the best ones first. (23.3) reorders the shortlist anyway. Measure end-to-end answer quality, not just index recall.

Key points

  • Exact search compares the query with every vector: perfect results, but slow at large scale.
  • Approximate nearest neighbour (ANN) indexes find most of the true nearest vectors far faster.
  • Recall is the share of true nearest neighbours an index returns; you tune indexes to trade recall for speed.
Hands-on labRuns in the Playground

Measure recall of an approximate search

Compare exact search with a cheap approximate search and measure recall@10 as you widen the candidate list.

You will have: A script that prints recall@10 and the work done for three candidate-list sizes.

Steps

  1. Read the setup: 2,000 random 16-dimension vectors and 20 queries, seeded with random.Random(7).
  2. Write exact_top(): compare the query with every vector and keep the best 10.
  3. Write approx_top(): pre-rank by the first 4 dimensions only, then fully score just the top C candidates.
  4. Compute recall@10 against exact search for C = 20, 100 and 400.

Done when

  • Exact search does 2,000 full comparisons per query.
  • Recall@10 rises as C grows.
  • At C = 400 (a fifth of the full comparisons) recall@10 is still only about 0.6: a crude pre-rank misses many true neighbours, which is why real ANN indexes use graphs or clusters.

Open in the Playground No API key needed.

Starter code (Python)
import random

rng = random.Random(7)
DIM, N = 16, 2000
VECS = [[rng.gauss(0, 1) for _ in range(DIM)] for _ in range(N)]
QUERIES = [[rng.gauss(0, 1) for _ in range(DIM)] for _ in range(20)]

def dot(a, b):
    return sum(x * y for x, y in zip(a, b))

def exact_top(q, k=10):
    # TODO: score every vector with dot(q, v) and return the ids of the best k
    return []

def approx_top(q, c, k=10):
    # TODO: rank all ids by dot(q[:4], v[:4]) (cheap), keep the top c, then score those fully
    return []

for c in (20, 100, 400):
    found = 0
    for q in QUERIES:
        found += len(set(exact_top(q)) & set(approx_top(q, c)))
    print(f"C={c}: recall@10 = {found / (10 * len(QUERIES)):.2f}")
Show a solution
import random

rng = random.Random(7)
DIM, N = 16, 2000
VECS = [[rng.gauss(0, 1) for _ in range(DIM)] for _ in range(N)]
QUERIES = [[rng.gauss(0, 1) for _ in range(DIM)] for _ in range(20)]

def dot(a, b):
    return sum(x * y for x, y in zip(a, b))

def exact_top(q, k=10):
    return sorted(range(N), key=lambda i: -dot(q, VECS[i]))[:k]

def approx_top(q, c, k=10):
    short = sorted(range(N), key=lambda i: -dot(q[:4], VECS[i][:4]))[:c]
    return sorted(short, key=lambda i: -dot(q, VECS[i]))[:k]

print(f"exact search: {N} full comparisons per query")
recalls = []
for c in (20, 100, 400):
    found = sum(len(set(exact_top(q)) & set(approx_top(q, c))) for q in QUERIES)
    recalls.append(found / (10 * len(QUERIES)))
    print(f"C={c}: recall@10 = {recalls[-1]:.2f}, full comparisons per query = {c}")
print("recall rises with C:", recalls == sorted(recalls))
Quick checkYour store holds 50 million vectors and exact search takes seconds per query. What's the usual approach?
How sure are you?
Pick an answer and how sure you are