# What Is Approximate Nearest-Neighbour Search?

> How approximate nearest-neighbour search finds similar items fast, what it trades away, and how to measure it, for your AI interview.

**In short:** Approximate nearest-neighbour search finds the stored vectors closest to a question without checking every one. It is much faster than exact search, but it can miss some true closest matches, so you measure recall.

AI and LLM interview question Q119, Retrieval-augmented generation (RAG). Intermediate, common (our estimate). From Venkat R. Murty's free Interview Kit: https://designervenkat.online/interview/ai/what-is-approximate-nearest-neighbour-search

## Say it in 30 seconds

I'd describe approximate nearest-neighbour search as finding the stored items closest in meaning to a question, without checking every one. Exact search checks every one. It is always right, but slow at scale. Approximate search checks only a few likely places, using an index built ahead of time. It is much faster, and it can miss some true matches. I measure that with recall, the share of the true top results the index returns, and I tune the search for the speed the team needs.

## Say it in 2 minutes

Picture a claims assistant at an insurer. A new claim comes in, and it must find the 10 past claims most like it. I store each claim as a vector, a list of numbers that stands for its meaning. Nearest-neighbour search finds the stored vectors closest to the new one.

Exact search compares the question with every stored vector. It always finds the true closest matches, but with 40 million notes that means 40 million comparisons for each question. Approximate search checks only a few likely places, found through an index I build in advance. It is much faster, and it can miss some of the true top 10.

I measure the trade as recall, the share of true top results the index returns. On real past claims, if it returns 8 of the 10 true matches, recall is 80%. I tune the search effort to lift recall, and I accept the extra time that costs.

The honest limit: an index can only find what the embedding model put close together. The embedding model is the one that turns each item into its vector. A better index doesn't fix a weak model, and it does not promise the true top results. I say that plainly, and I explain how I would measure it.

## What is approximate nearest-neighbour search, in plain words?

When an AI app searches by meaning, it turns the question and each stored item into a vector (an embedding: a list of numbers that places it somewhere in a large space). Items with similar meaning sit close together. Nearest-neighbour search asks one thing: which stored vectors are closest to this question?

Exact search answers that by measuring the distance to every stored vector. It is always right, but the work grows with every item you add. Approximate search accepts some risk of missing a true close match, in return for checking only part of the store.

Think of a senior claims handler at an insurer. She cannot reread every closed file for each new claim, so she goes straight to the few cabinets where similar cases tend to sit. She might miss one old file, but she answers in minutes. An approximate index does the same for a claims assistant that searches 40 million stored notes.

- **Vector:** A list of numbers that stands for the meaning of a piece of text.
- **Nearest neighbour:** A stored vector closest to the question, by distance.
- **Exact search:** Checks every stored vector. Always right, but slow at scale.
- **Approximate search:** Checks some likely places. Fast, and it can miss some.
- **Recall:** The share of the true top results that the search returned.

## Why not compare with everything?

Exact search is the baseline. It is right every time, and for a small set it is often fast enough. Trouble starts with scale. Google Research's ScaNN work is about maximum inner-product search (MIPS), a closely related task to nearest-neighbour search. Its authors say the set of embeddings is often too large for exhaustive search, so their answer is approximate MIPS algorithms that trade some accuracy for speed.

- **Exact: Check every stored vector.** Always finds the true closest matches. The work grows with every item added.
- **Approximate: Check a few likely places.** Far less work per question. It can miss a true close match, so you measure how often.

> "This necessitates the use of approximate MIPS algorithms that exchange some accuracy for a significant speedup over brute-force search." (Google Research, on ScaNN)

*Diagram, Exact and approximate search side by side: The same question takes two paths. The exact path scores every note and never misses. The approximate path scores a few places, so it is quicker, but it can miss a true match.*
1. The question is compared with every stored note.
2. The question goes to the index, which picks the likely places.
3. Every note was checked, so the answer is exact.
4. Only the picked places were checked, so some true matches can be missed.

## How do the fast methods skip most of the data?

Here are three families. Graphs link each vector to near neighbours, in layers, so a search hops toward the answer. HNSW (Hierarchical Navigable Small World) is one example. Its paper says it "incrementally builds a multi-layer structure" and "allows a logarithmic complexity scaling".

Cells cut the space into regions and file each vector under its nearest region. At search time you check only the few regions nearest the question. Compression stores each vector as a shorter code, so scoring is quicker and less memory is needed. Google's ScaNN work focuses on compressing dataset vectors for fast approximate distance computations.

*Diagram, How cells cut the search down: Cells are built once. A question is compared with the 25 centres, picks the two nearest, and scores only their notes. The 615 and 74% figures come from a small demo, so they show the idea only.*
1. The cells are built once, before any question arrives.
2. The question is compared with the 25 cell centres.
3. Only the notes in the two chosen cells are scored.
4. The ten closest are kept. In the demo that is 74% of the true ten.

Here is the idea in plain Python, using only the standard library and a made-up index of 5,000 claim notes.

```python
import random

# A made-up index: 5,000 claim notes, each 8 numbers. The seed makes every run the same.
random.seed(7)
N, DIM, CELLS = 5000, 8, 25
notes = [[random.gauss(0, 1) for _ in range(DIM)] for _ in range(N)]

def dist2(a, b):
    return sum((x - y) ** 2 for x, y in zip(a, b))

def closest(q, pool, k=10):
    return set(sorted(pool, key=lambda i: dist2(q, notes[i]))[:k])

# Build: pick 25 notes as cell centres, then file every note under its nearest centre.
centres = random.sample(range(N), CELLS)
cells = {c: [] for c in centres}
for i in range(N):
    cells[min(centres, key=lambda c: dist2(notes[i], notes[c]))].append(i)

# Search: compare only the notes in the 2 cells nearest the question.
queries = [[random.gauss(0, 1) for _ in range(DIM)] for _ in range(50)]
found, checked = 0, 0
for q in queries:
    probe = sorted(centres, key=lambda c: dist2(q, notes[c]))[:2]
    pool = [i for c in probe for i in cells[c]]
    checked += len(pool)
    # Ground truth: the exact answer, found by checking all 5,000 notes.
    found += len(closest(q, range(N)) & closest(q, pool))
print(f"average notes checked: {checked / len(queries):.0f} of {N}")
print(f"recall at 10: {found / (10 * len(queries)):.2f}")
```

Output:

```text
average notes checked: 615 of 5000
recall at 10: 0.74
```

## How do you know the fast answer is good enough?

Recall is the share of the true top results that the fast index returns. Compare the top 10 from each path and count the matches.

> "Recall@k is a commonly used metric for nearest neighbor search accuracy, which measures the proportion of the true nearest k neighbors that are present in an algorithm's returned k neighbors." (Google Research, on ScaNN)

A worked case: a claims team asks for the 10 closest past notes to a new claim. Exact search gives 10 true matches. The approximate index returns 8 of them. Recall is 80%, because it found 8 of the 10 that exact search found.

To measure it, take a sample of real past questions, run both paths, and average the recall. Measure against the exact search results.

- **Search effort:** How many candidates the index checks for each question. Microsoft's vector search docs call this efSearch, the number of nearest neighbours used during search.
- **Build effort:** How hard the index works when it is built. The same docs call this efConstruction, the number used during indexing.
- **The trade:** Raising search effort usually lifts recall but slows each query. Raising build effort makes the index slower to build, and recall can rise too. Re-measure after each change.

> **Tip:** Senior answer: name the number you report (recall at 10, on real questions) and what you do when it is low. Raise the search effort, or send that slice of queries to exact search.

## What does the interviewer want to hear?

**A strong answer covers**

- [ ] A plain definition: find the stored vectors closest to a question, without checking all of them.
- [ ] Exact versus approximate, and why scale forces the choice.
- [ ] The main families in plain words: graphs such as HNSW, cells, and compression.
- [ ] Recall: the share of true top results found, measured on real questions.
- [ ] The knob: search effort, which buys recall at the cost of speed.
- [ ] The honest limit: misses are possible, and a better index can't fix a weak embedding model.

**Common traps**

- Trap: "Approximate means random, so the results are rubbish." Better: It returns close matches on purpose. Measure recall, so you know how often it misses.
- Trap: "Approximate search is always faster, so use it for everything." Better: For a small set, exact search is simple and always right. Choose by size and by the recall you measured.
- Trap: "The vector database does the search, so the answer is always right." Better: The index trades accuracy for speed. Only exact search guarantees the true top results.

## Can you spot the trade-off?

**Spot the risk:** A team swaps exact claims search for an approximate index and says the top results look the same. What did they skip?

A. Nothing. Approximate results are always identical to exact ones.
B. They never measured recall on real claims, so they don't know how many true matches they now miss.
C. The index needs a bigger model to run.
D. Queries got slower, which means the index is broken.

**Answer:** B. Approximate search can miss true matches. Without a recall figure on real questions, 'the same results' is only an impression.

**Quick check:** A claims search returns 8 of the true 10 closest notes. What is its recall at 10?

A. 8%
B. 80%
C. 10%
D. Recall can't be measured for a search like this

**Answer:** B. Recall is the share of the true top results that were found: 8 of 10, which is 80%.

## Can you answer these from memory?

**Flash cards**

- **What is approximate nearest-neighbour search?** Finding the closest stored vectors by checking only a few likely places.
- **Exact or approximate: which is always right?** Exact. Approximate trades some chance of misses for speed.
- **What is recall?** The share of the true top results that the index actually returns.
- **Name three fast-method families.** Graphs such as HNSW, cells (regions the space is cut into), and compressed vectors.
- **What does a higher search effort do?** Usually raises recall and slows each query. Measure both.
- **Does a better index fix a weak embedding model?** No. The index can only find what the model placed close together.

## Likely follow-up questions

- Q117 What is a vector database? https://designervenkat.online/interview/ai/what-is-a-vector-database
- Q118 Cosine vs dot product vs Euclidean distance? https://designervenkat.online/interview/ai/cosine-vs-dot-product-vs-euclidean-distance
- Q120 How does HNSW work? https://designervenkat.online/interview/ai/how-does-hnsw-work
- Q121 How does IVF indexing work? (full answer coming)
- Q122 What is product quantization? (full answer coming)
- Q123 What is hybrid search (BM25 + vectors)? https://designervenkat.online/interview/ai/what-is-hybrid-search

## Learn it in depth

- [Vector DBs](https://designervenkat.online/learn/ai-engineering/vector-dbs)
- [Indexing Embeddings](https://designervenkat.online/learn/ai-engineering/indexing-embeddings)
