Sub topic 8
Vector Indexes and Approximate Nearest Neighbor Search
This chapter assumes you can read basic Python, know what an embedding is, and understand cosine similarity from the previous chapter. It explains why brute-force search stops scaling and how an index trades a little accuracy for a lot of speed.
Why brute force stops scaling
The top_k function below scores every stored vector against the query. This is exact nearest-neighbor search, and it is always correct.
import math
def cosine(a, b):
dot = sum(x * y for x, y in zip(a, b))
na = math.sqrt(sum(x * x for x in a))
nb = math.sqrt(sum(y * y for y in b))
return dot / (na * nb) if na and nb else 0.0
def top_k(query_vec, index, k=3):
# index is a list of (text, vector) pairs
scored = [(cosine(query_vec, vec), text) for text, vec in index]
scored.sort(key=lambda pair: pair[0], reverse=True)
return scored[:k]The cost grows linearly. With N vectors of dimension d, each query does about N × d multiplications. For 10,000 chunks this is fine. For 50 million chunks of 1,024 dimensions, each query needs tens of billions of operations, which is too slow for an interactive application.
What an index does
A vector index is a data structure that lets a search skip most vectors. Approximate nearest neighbor (ANN) search returns neighbors that are very likely, but not guaranteed, to be the true closest ones. The fraction of true neighbors it finds is called its recall. You accept, for example, 95% recall in exchange for queries that are 100 times faster.
Common index types
| Index | Idea | Strengths | Costs |
|---|---|---|---|
| Flat | Compare against every vector | Exact, simple | Slow at scale |
| IVF (inverted file) | Cluster vectors, search only the nearest clusters | Fast, modest memory | Needs a training step, misses neighbors near cluster edges |
| HNSW | Layered graph, walk toward the query | High recall, fast queries | High memory, slower inserts |
| PQ (product quantization) | Compress vectors into short codes | Large memory savings | Lower precision |
These can be combined. A common production setup is IVF with PQ for very large collections, or HNSW when memory is available.
The tuning knobs
Each index exposes parameters that move you along the accuracy and speed curve.
- IVF
nprobe: how many clusters to search. Higher means better recall and slower queries. - HNSW
efSearch: how many candidates to track while walking the graph. Higher means better recall and slower queries. - HNSW
M: how many links each node keeps. Higher means better recall and more memory.
Measure recall on your own data. Build a flat index as ground truth, run a sample of queries on both, and compare the results with the recall_at_k function:
def recall_at_k(retrieved_ids, relevant_ids, k):
relevant = set(relevant_ids)
if not relevant:
return 0.0
hits = set(retrieved_ids[:k]) & relevant
return len(hits) / len(relevant)Here the "relevant" ids are the ones the exact search returned, and the "retrieved" ids come from the ANN index.
Common errors
- Skipping the recall check. An index tuned for speed can silently drop the one chunk that held the answer.
- Mixing metrics. If the index uses inner product but your embeddings were meant for cosine, normalize the vectors to length 1 first.
- Filtering after the search. If you take the top 10 and then drop results by metadata, you may end up with too few. Either use the index's filtering support or retrieve more candidates.
- Forgetting rebuilds. Some indexes degrade as data changes and need retraining or rebuilding.
Exercise
Your IVF index returns results quickly, but recall against a flat index is only 80%. Name one parameter change that raises recall and say what it costs.
Show answer
Increase nprobe so more clusters are searched. Recall rises because neighbors near cluster boundaries are more likely to be found, but each query scores more vectors and gets slower.