Sub topic 9
Scaling up: approximate nearest-neighbor search (IVF, HNSW)
This chapter assumes you can write basic Python and NumPy, and that you have built the exact top-k search from the earlier chapter, where one matrix-vector product scores every document. Here you will see why that approach stops working at scale. You will also learn how the two most common approximate indexes, IVF and HNSW, trade a little accuracy for a large speedup.
When exact search stops being enough
Exact search compares the query with every stored vector. With N vectors of dimension d, each query costs about N × d multiply-adds and must read all N × d floats from memory.
- 10,000 vectors of 384 dimensions: about 3.8 million multiply-adds per query. This takes milliseconds.
- 1,000,000 vectors of 384 dimensions: about 384 million multiply-adds, and 1.5 GB of float32 data to scan per query (384 × 4 bytes × 1,000,000). This is tens to hundreds of milliseconds on a CPU, depending on hardware and batching.
- 100,000,000 vectors: the data no longer fits in the memory of one ordinary machine, and a full scan per query is impractical.
Approximate nearest-neighbor (ANN) search gives up the guarantee of returning the true top-k. In return it examines only a small fraction of the vectors. The measure of what you gave up is recall against exact search: of the true top-k, what fraction did the index return?
Exact search is still the right choice in some cases:
- Your collection is below roughly 100,000 vectors.
- You need guaranteed results.
- You need a ground truth to measure ANN indexes against.
The idea shared by all ANN indexes
Every ANN index builds a structure over the vectors ahead of time. At query time it uses that structure to pick a small set of candidates, then scores only those candidates with real distances. Indexes differ in how the structure is built and what it costs:
| Index | Structure | Build cost | Memory beyond raw vectors | Main query knob |
|---|---|---|---|---|
| Flat (exact) | None | None | None | None |
| IVF | Clusters with inverted lists | Training (k-means) plus adding | Small (centroids and ids) | `nprobe` |
| HNSW | Layered proximity graph | High (graph construction) | Substantial (links per vector) | `efSearch` |
IVF: search only the nearest clusters
IVF stands for inverted file. Training runs k-means on the vectors to find nlist centroids. Each vector is then assigned to its nearest centroid and stored in that centroid's list.
At query time:
- Compare the query with the
nlistcentroids. - Pick the
nprobeclosest centroids. - Scan only the vectors in those lists and return the best k.
With nlist clusters of roughly equal size and nprobe lists scanned, a query touches about nlist + nprobe × N / nlist vectors instead of N. A common starting point for nlist is on the order of the square root of N, such as 1,000 to 4,000 for a million vectors.
The failure mode is easy to see. If the true nearest neighbor sits just across a cluster boundary, and its cluster is not among the nprobe closest, the query misses it. Raising nprobe fixes this by scanning more lists, at proportionally higher cost. Setting nprobe = nlist makes IVF exact.
IVF has two practical consequences:
- It needs a training step on a representative sample of vectors. If your data distribution changes later, the centroids go stale and recall drops until you retrain.
- It is cheap in memory, and it combines well with compression such as product quantization (the IVF-PQ variants in FAISS), which stores each vector in tens of bytes instead of 1,536.
HNSW: walk a graph toward the query
HNSW stands for Hierarchical Navigable Small World. It builds a graph in which each vector is linked to nearby vectors. The graph has several layers. The top layers contain few vectors and have long-range links. The bottom layer contains every vector.
A search works like this:
- Enter at the top layer and greedily move to whichever neighbor is closest to the query.
- When no neighbor improves the distance, drop to the next layer, starting from the best node found so far.
- At the bottom layer, run a wider best-first search that keeps a candidate list of size
efSearch, and return the best k found.
The top layers act like an express road network, and the bottom layer does the fine-grained local search. Queries are typically fast and reach high recall, which is why HNSW is a common default in vector databases.
Three parameters matter:
M: the number of links per node. A largerMgives higher recall and a larger index.efConstruction: the candidate list size while building. A larger value gives a better graph and a slower build.efSearch: the candidate list size while querying. A larger value gives higher recall and slower queries. It must be at least k.
Costs to plan for:
- The graph links add memory on top of the raw vectors. With
M = 32, the bottom layer alone stores up to about 64 links per vector, roughly 256 bytes at 4 bytes each. - Building is slow compared with IVF.
- Deleting vectors is awkward, because removing a node leaves holes in the graph. Many implementations mark vectors as deleted instead and rebuild periodically.
Measuring the trade-off yourself
Do not trust default settings. Build an exact index, treat its answers as ground truth, and measure each ANN index against it on queries that are not in the indexed set. The script below uses random unit vectors, so it runs without a model download. Random high-dimensional vectors have no cluster structure, which makes them a hard case for ANN. Expect lower recall than on real text embeddings, and use the numbers to see the trend rather than as a benchmark.
import time
import faiss
import numpy as np
d, n, n_queries, k = 384, 20000, 100, 10
rng = np.random.default_rng(0)
vectors = rng.standard_normal((n, d)).astype("float32")
queries = rng.standard_normal((n_queries, d)).astype("float32")
faiss.normalize_L2(vectors)
faiss.normalize_L2(queries)
# Ground truth from exact search.
flat = faiss.IndexFlatIP(d)
flat.add(vectors)
_, truth = flat.search(queries, k)
def recall(found, truth):
hits = [len(set(f) & set(t)) / len(t) for f, t in zip(found, truth)]
return float(np.mean(hits))
# IVF: train centroids first, then add vectors.
nlist = 128
quantizer = faiss.IndexFlatIP(d)
ivf = faiss.IndexIVFFlat(quantizer, d, nlist, faiss.METRIC_INNER_PRODUCT)
ivf.train(vectors)
ivf.add(vectors)
print("IVF")
for nprobe in (1, 4, 16, 64):
ivf.nprobe = nprobe
start = time.perf_counter()
_, ids = ivf.search(queries, k)
ms = (time.perf_counter() - start) * 1000
print(f" nprobe={nprobe:3d} recall@{k}={recall(ids, truth):.3f} {ms:.1f} ms")
# HNSW: no training step, but a slower build.
hnsw = faiss.IndexHNSWFlat(d, 32, faiss.METRIC_INNER_PRODUCT)
hnsw.hnsw.efConstruction = 200
hnsw.add(vectors)
print("HNSW")
for ef in (16, 64, 256):
hnsw.hnsw.efSearch = ef
start = time.perf_counter()
_, ids = hnsw.search(queries, k)
ms = (time.perf_counter() - start) * 1000
print(f" efSearch={ef:3d} recall@{k}={recall(ids, truth):.3f} {ms:.1f} ms")Three points about this script:
IndexIVFFlatraises an error if you add vectors before callingtrain.- The code passes
METRIC_INNER_PRODUCTexplicitly.IndexHNSWFlatdefaults to L2 distance. On unit vectors, L2 and inner product give the same ranking, but the scores differ, so be consistent with the rest of your pipeline. - Recall rises with
nprobeandefSearch, and so does latency. Pick the cheapest setting that meets your recall target.
For tiny timings like these, the numbers are noisy. Repeat the measurement and run on realistic data before drawing conclusions.
Choosing an index
Use these criteria in order:
- Collection size. Up to about 100,000 vectors, use exact search. It is simple, has no tuning, and is often fast enough.
- Memory budget. If raw vectors barely fit in RAM, HNSW's link overhead may not fit. IVF, especially with product quantization, uses less memory.
- Update pattern. If vectors are added and removed constantly, HNSW handles inserts well but deletes poorly. IVF handles inserts well but needs retraining if the data drifts.
- Latency and recall targets. HNSW usually gives the best recall at low latency. IVF is competitive when you can afford a larger
nprobe. - Build time. If you rebuild frequently, IVF is cheaper to build.
Whatever you pick, measure recall against exact search on your own data and queries. Also remember that ANN recall is only one source of loss. A missed result caused by the embedding model or chunking looks the same to the user but cannot be fixed by tuning the index.
Exercise
An IVF index with nlist=1000 and nprobe=10 returns only 70% of the true top-10 on your labeled queries. Name two changes that would raise recall, and say what each one costs.
Show answer
Raise nprobe (for example to 50): more lists are scanned, so recall rises, but each query does proportionally more work and takes longer. Alternatively, lower nlist, or retrain on a more representative sample: larger clusters mean a neighbor is less likely to fall in an unscanned list, but each list is bigger and slower to scan, and retraining costs build time. Switching to HNSW is a third option, at the cost of more memory and a slower build.
Exercise
You set efSearch=5 on an HNSW index and ask for k=10 results. What is wrong, and how do you fix it?
Show answer
efSearch is the size of the candidate list during the bottom-layer search, so it must be at least k. With efSearch=5 the search cannot track enough candidates to return 10 good results. Set efSearch to at least k, and usually well above it (for example 64 or more), then measure recall against an exact index.