RAG and vector searchLoading progress…

Inverted files

Trace IVF and HNSW search and explain how candidate exploration trades latency for recall.

Inverted files: search only some clusters

An inverted file (IVF) index first groups the vectors into clusters around coarse centroids. At query time it finds the centroids nearest the query and scans only the vectors in those lists. With 102,400 vectors in 1024 cells (about 100 each), probing 8 cells scans about 800 vectors instead of 102,400. The price: a true neighbour sitting in a cell that was not probed is never seen.

query position5.1nprobe (cells searched)1
centroid 0centroid 10centroid 200123456789q = 5.1
probe order (nearest centroid first): 10, 0, 20 searched cells: 10 candidates scanned: 3 of 10 IVF answer: id 3 (x = 7) exact answer: id 2 (x = 4.6) MISSED the true neighbour

Try query 5.1 with nprobe 1: the point at 4.6 lives in the neighbouring cell, so it is never looked at. At scale, 102,400 vectors in 1024 cells means about 100 per cell, so probing 8 cells scans about 800 vectors.

Query 5.1 with nprobe = 1: which point is missed?

Predict first. Does searching only the nearest coarse centroid guarantee the exact nearest original vector?

Chapter context

An approximate index organizes vectors so a query can avoid most comparisons. Clustering and graph navigation use different mechanisms to choose candidates, and their build settings influence later search quality.

Chapter reference: math, worked example & code

This section belongs to the whole chapter, so it is the same on every lesson in it and may cover a different lesson's topic. The code for the experiment you just ran is inside the experiment itself.

Math and notation

Under the simplifying assumption of equally sized IVF lists, N vectors, C cells and p probes produce approximately

Ncandidates≈Np/C.N_{candidates}\approx Np/C.

Add coarse scoring, uneven list sizes and any reranking costs separately. HNSW has no equivalent universal fixed candidate-count formula.

Worked example

For 102,400 vectors evenly divided among 1024 cells, a cell has 100 vectors. Probing eight cells scans about 800 candidates, compared with 102,400 in a full scan. This excludes coarse-centroid comparisons and says nothing by itself about recall.

Reference code

The following example uses the Python standard library and does not call a remote service.

total,cells,probes=102400,1024,8
assert total/cells == 100
assert total*probes/cells == 800
assert total/(total*probes/cells) == 128

Python examples are provided for study and local execution; this page does not execute Python.

Common mistakes

An average candidate count is not an actual worst-case bound. More graph edges consume memory. Approximate search settings must be evaluated against the current corpus and metric.