Sub topic 8
Vector Indexes and Approximate Nearest Neighbor Search
This chapter assumes you know basic Python, vectors and the dot product, and the brute-force top_k function from the previous chapter. You should also know what an embedding is and why cosine similarity compares two of them.
Why brute force stops working
The exact search from the previous chapter scores every stored vector against the query. Its cost grows linearly with the number of vectors. For N vectors of dimension d, one query needs about N × d multiplications.
Here is a rough sense of scale:
| Stored chunks | Dimension | Multiplications per query |
|---|---|---|
| 10,000 | 768 | about 7.7 million |
| 1,000,000 | 768 | about 770 million |
| 100,000,000 | 768 | about 77 billion |
At 10,000 chunks, pure Python is fine. At a million, a single query in pure Python takes seconds, and even optimized libraries become a cost issue under load. A vector index is a data structure that lets you find near neighbors without scoring everything.
An approximate nearest neighbor (ANN) index gives up a guarantee of exactness to gain speed. It may miss a true top-k result, but it examines only a small fraction of the vectors.
Recall: the price of approximation
The accuracy of an ANN index is measured as recall against exact search. For a set of test queries, compute the true top-k with brute force. Then compute what the index returns. Recall@k is the fraction of the true neighbors that the index found.
This is the same idea as the recall_at_k function you will use later to evaluate retrieval. Here the "relevant" set is the exact neighbors instead of human-labeled documents. The two meanings are different. ANN recall tells you how faithfully the index copies brute force. Retrieval recall tells you whether the right documents were found at all.
def ann_recall(exact_ids, approx_ids):
exact = set(exact_ids)
if not exact:
return 0.0
return len(exact & set(approx_ids)) / len(exact)
print(ann_recall([1, 2, 3, 4, 5], [1, 2, 3, 9, 5])) # 0.8An index at 0.95 recall returns, on average, 95 of the true top 100. For RAG, that is often acceptable. The embedding model is already an imperfect measure of relevance, so a small loss from the index rarely matters compared with chunking or embedding quality.
Three families of index
Most indexes belong to one of three families.
Flat index
A flat index stores vectors in a plain array and scans all of them. It is exact. It is the baseline for measuring other indexes.
IVF: inverted file index
An IVF index first clusters the vectors, usually with k-means. Each cluster has a centroid, and each vector is assigned to its nearest centroid. At query time, the index compares the query to the centroids, picks the closest few clusters, and scans only the vectors in them.
The key parameters are:
nlist: the number of clusters, chosen at build time.nprobe: the number of clusters scanned per query, chosen at query time.
Raising nprobe raises recall and latency together. If a true neighbor sits in a cluster you did not scan, you miss it. This happens most often when the query lies near a cluster boundary.
HNSW: hierarchical navigable small world graph
An HNSW index builds a graph in which each vector is a node linked to nearby nodes. The graph has several layers. The top layer is sparse and has long links. Lower layers are denser. A search starts at the top, moves greedily toward the query, drops a layer, and repeats until it reaches the bottom layer, where it explores a wider neighborhood.
The key parameters are:
M: how many links each node keeps. Larger values improve recall and use more memory.efConstruction: how thorough the search is while building the graph. Larger values give a better graph and a slower build.efSearch: how many candidates are tracked during a query. Larger values raise recall and latency.
Comparing the families
| Property | Flat | IVF | HNSW |
|---|---|---|---|
| Accuracy | Exact | Approximate | Approximate |
| Query speed | Slowest | Fast | Very fast |
| Build cost | None | Needs clustering (training) | Slow graph build |
| Memory | Vectors only | Vectors plus centroids | Vectors plus graph links |
| Main query knob | None | `nprobe` | `efSearch` |
| Handles inserts | Trivially | Yes, but clusters drift | Yes, with cost |
HNSW is a common default in vector databases because it gives high recall at low latency. Its main cost is memory, since the graph is usually held in RAM. IVF uses less memory and works well when combined with compression.
Compression with quantization
Memory often limits index size more than compute does. One million 768-dimensional vectors stored as 32-bit floats take about 3 GB. At 100 million, that is about 300 GB.
Quantization shrinks vectors:
- Scalar quantization stores each number in 8 bits instead of 32, a 4x saving, with a small loss in accuracy.
- Product quantization splits each vector into sub-vectors and replaces each with a short code from a learned codebook. Savings of 16x to 64x are common, at a larger accuracy cost.
Compressed distances are approximate, so a common pattern is to search the compressed index for extra candidates, such as 100. Then you rescore those candidates with the original full-precision vectors. This costs little and recovers much of the lost recall.
The distance metric must match the embeddings
An index is built for one metric: cosine, dot product, or Euclidean (L2) distance. Using the wrong one is a quiet error, because the index still returns results, just poor ones.
If your embedding model produces unit-length vectors, cosine similarity and dot product give the same ranking. Many indexes implement only dot product or L2. A common approach is to normalize vectors to length 1 and use dot product. The sketch below shows the normalization step.
import math
def normalize(vec):
norm = math.sqrt(sum(x * x for x in vec))
return [x / norm for x in vec] if norm else vec
a = normalize([3.0, 4.0])
print(a) # [0.6, 0.8]
print(sum(x * x for x in a)) # 1.0 (unit length, up to float rounding)Normalize both the stored vectors and the query. Normalizing only one of them breaks the equivalence.
Using an index in practice
Here is a minimal example with the FAISS library, which supports flat, IVF, and HNSW indexes. It builds an HNSW index and compares it with exact search. Install it with pip install faiss-cpu numpy.
import numpy as np
import faiss
rng = np.random.default_rng(0)
d, n = 64, 20000
vectors = rng.standard_normal((n, d)).astype("float32")
faiss.normalize_L2(vectors) # unit length, so inner product equals cosine
queries = rng.standard_normal((100, d)).astype("float32")
faiss.normalize_L2(queries)
k = 10
exact = faiss.IndexFlatIP(d)
exact.add(vectors)
_, exact_ids = exact.search(queries, k)
hnsw = faiss.IndexHNSWFlat(d, 32, faiss.METRIC_INNER_PRODUCT) # M = 32
hnsw.hnsw.efConstruction = 200
hnsw.add(vectors)
for ef in (16, 64, 256):
hnsw.hnsw.efSearch = ef
_, approx_ids = hnsw.search(queries, k)
recalls = [
len(set(e) & set(a)) / k
for e, a in zip(exact_ids, approx_ids)
]
print(f"efSearch={ef}: recall@{k} = {sum(recalls) / len(recalls):.3f}")Random vectors are harder for graph indexes than real embeddings, so expect lower recall here than on real text. The pattern still holds: recall rises with efSearch, and so does query time.
Tuning and edge cases
Follow this order when tuning:
- Build a test set of real queries and compute exact top-k results for them.
- Pick an index type and build parameters.
- Sweep the query parameter (
nprobeorefSearch) and record recall and latency. - Choose the cheapest setting that meets your recall target, such as 0.95.
Several gotchas come up often:
- Filters can hurt recall. Metadata filtering (covered in the next chapter) applied after the ANN search may leave fewer than k results. Filtering during the search is better, but support varies by system. Highly selective filters may force a fall back to exact search over the matching subset.
- Deletes are not always real. Many graph indexes mark nodes as deleted and leave them in place. Heavy churn degrades the index until you rebuild it.
- IVF needs representative training data. If you train clusters on data that differs from what you later insert, clusters become unbalanced and recall drops.
- Index and model are coupled. If you change the embedding model, every vector must be re-embedded and the index rebuilt. Vectors from different models cannot be mixed.
- Recall depends on data. Settings tuned on one corpus may not carry over to another.
Exercise
An IVF index has nlist = 1000 and you query with nprobe = 5. A user reports that an obviously relevant chunk is never returned, though exact search finds it. Name the likely cause and two ways to fix it.
Show answer
The chunk's vector most likely sits in a cluster that was not among the 5 closest to the query, often because it lies near a cluster boundary. Fixes: raise nprobe (more recall, more latency), or switch to or add an HNSW index. Re-training the clusters on representative data can also help. Confirm the cause by measuring recall against a flat index.
Exercise
Your embedding model returns vectors that are not unit length, and your index uses inner product. The ranking differs from your earlier cosine-based brute-force results. What do you change?
Show answer
Normalize both the stored vectors and the query vectors to length 1 before indexing and searching. With unit vectors, inner product gives the same ranking as cosine similarity.