Foundations to Frontier
Tests
F. NLP and Large Language Models › F10 Retrieval-Augmented Generation

Vector databases and ANN search

Dense retrieval compares a query embedding with millions of document embeddings, and computing every distance is too slow at scale. Approximate nearest neighbour (ANN) indexes trade a little recall for large savings in time and memory. This page covers inverted-file indexes (IVF), product quantisation (PQ), graph indexes (HNSW), how vector databases combine them with filtering and updates, and how to measure recall. In the exercises you write exact cosine search, IVF assignment and PQ encoding, then compare indexes on 10000 clustered vectors. IVF with 4 of 100 lists found 99.9% of the true top 10 with 5% of the distance computations. PQ at 16 times compression found 47% alone and 99.3% after reranking 100 candidates. A pure nearest-neighbour graph found 2%, because it never left its starting cluster. Adding two random long-range links per node and a sparse upper layer, as HNSW does in effect, reached 100% with under 5% of the work.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Finding the nearest book without checking every shelf

To find the most similar of ten million documents you could compare the question with every one, but that is slow. Libraries solve this with sections: go to the right section, then search only there. Vector indexes do the same: IVF groups vectors into clusters and searches only the closest few; graph indexes hop from neighbour to neighbour towards the query; quantisation stores compressed vectors so more fit in memory. The demo shows how searching more clusters raises recall and cost together.

Retrieval lab
Probing 4 of 256 clusters scans 1.6% of vectors for recall@10 of 83%.
Why engineers care

Every RAG system over a large document collection relies on an approximate index; its recall is a ceiling on the whole system’s accuracy.

📝 Quick check (Level 0)
0/3 answered
  1. 1. ANN stands for…
  2. 2. IVF searches…
  3. 3. ANN trades…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

By hand

  • Exact (flat) search: compute all n distances; perfect recall; fine up to about a million vectors on a GPU or with batching.
  • IVF: k-means into n_lists clusters; at query time compare with all centroids, then scan the nprobe nearest lists. Cost ≈ n_lists + nprobe · n / n_lists.
  • PQ: split each vector into m sub-vectors, quantise each with its own 256-entry codebook, store m bytes. Distances come from a per-query lookup table (asymmetric distance computation). Often combined: IVF-PQ, with reranking on full vectors.
  • HNSW: a multi-layer proximity graph; search starts at the sparse top layer and greedily descends, then runs a beam search (width ef) on the bottom layer. High recall and speed, but memory for links and slower inserts.
  • Other: ScaNN (anisotropic quantisation), DiskANN (graph on SSD), scalar and binary quantisation.
  • Vector databases: add persistence, updates and deletes, metadata filtering, replication and hybrid search; FAISS is a library, Qdrant, Milvus, Weaviate, pgvector are databases (F16-4).
  • Metric: recall@k against exact search, as a function of queries per second and memory.
📝 Quick check (Level 1)
0/3 answered
  1. 1. IVF cost per query is about…
  2. 2. PQ stores per vector…
  3. 3. HNSW search starts at…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.

Building and tuning an index

Exercise 1.

  • Exact cosine top-k search.
  • Assign vectors to IVF lists.
  • Encode a vector with product quantisation.

Practice.

  • FAISS: IndexFlatIP, IndexIVFFlat, IndexIVFPQ, IndexHNSWFlat; set nprobe or efSearch at query time.
  • Normalise embeddings for cosine similarity and use inner product.
  • Tune on a held-out query set: plot recall@10 against latency; pick the cheapest setting meeting the recall target.
  • For under a million vectors, exact or HNSW search is usually enough; beyond that, IVF-PQ or disk-based indexes.
  • Filtering by metadata can break graph search (too few allowed nodes); use pre-filtering or filter-aware indexes.
import faiss, numpy as np
X = X.astype("float32"); faiss.normalize_L2(X)
quant = faiss.IndexFlatIP(X.shape[1])
index = faiss.IndexIVFPQ(quant, X.shape[1], 1024, 64, 8, faiss.METRIC_INNER_PRODUCT)
index.train(X); index.add(X)
index.nprobe = 16
D, I = index.search(Q, 10)
🐍 Exercise 1: exact search, IVF and PQ
Write exact cosine top-k, IVF list assignment and PQ encoding.
📝 Quick check (Level 2)
0/3 answered
  1. 1. FAISS's IVF parameter set at query time:
  2. 2. For cosine similarity, first…
  3. 3. Tune an index by…

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory

IVF cost. With n vectors in L equal lists, a query costs L + p·n/L distance computations, minimised at L ≈ √(p·n). Recall depends on how often a true neighbour sits in a list whose centroid is not among the p nearest: neighbours near cluster boundaries.

PQ error. PQ approximates x by concatenated codewords; the distance error is the quantisation error of the sub-vectors. With m bytes per vector the codebook has 256^m effective centroids, far more than k-means could train directly. Ranking by approximate distance then reranking the top few hundred with exact vectors recovers most of the recall.

Navigable graphs. Greedy search on a graph succeeds when every node can reach the query’s neighbourhood in few hops. A k-nearest-neighbour graph is locally good but can split into disconnected clusters; navigable small-world graphs add long-range links, and HNSW’s upper layers provide a coarse-to-fine path from any entry point to the right region.

📝 Quick check (Level 3)
0/3 answered
  1. 1. Optimal IVF list count grows like…
  2. 2. PQ recall is restored by…
  3. 3. A pure kNN graph can fail because…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

History.

  • H. Jégou, M. Douze and C. Schmid, “Product quantization for nearest neighbor search” (TPAMI 2011).
  • Y. Malkov and D. Yashunin, “Efficient and robust approximate nearest neighbor search using hierarchical navigable small world graphs” (TPAMI 2018).
  • J. Johnson, M. Douze and H. Jégou, “Billion-scale similarity search with GPUs” (FAISS, 2017); R. Guo et al., ScaNN (2020); S. Subramanya et al., DiskANN (2019).

Exercise 2. 10000 vectors in 32 dimensions from 50 well-separated clusters; 100 queries; recall@10 against exact search; cost = distance computations per query (exact: 10000).

index recall@10 cost
IVF, 100 lists, nprobe 1 0.769 239
IVF, nprobe 4 0.999 530
IVF, nprobe 16 1.000 1663
PQ, 8 bytes per vector (vs 128) 0.473 (lookups)
PQ + rerank top 100 0.993 (lookups) + 100
kNN graph (16 links), ef 40 0.020 184
kNN graph + upper layer of 100 0.870 296
+ 2 random long links, no upper layer 0.990 538
+ long links + upper layer, ef 10 0.964 325
+ long links + upper layer, ef 40 1.000 477
+ long links + upper layer, ef 160 1.000 929
  • IVF: one probe missed neighbours across cluster boundaries; four probes were near-exact at 5% of the work.
  • PQ: 16 times smaller vectors ranked coarsely, but as a candidate generator for exact reranking it was excellent.
  • Graphs: the first version, a plain nearest-neighbour graph, failed completely: the search never left the starting cluster. An upper layer picking a nearby entry point fixed most queries; random long-range links made the graph navigable, and both together reached perfect recall.
  • Seeds 1 and 2: IVF nprobe 4 0.998 and 0.995; PQ + rerank 0.993 on both; long links + upper layer at ef 40 1.0 on both.
  • Caveat: real HNSW builds links incrementally with a neighbour-selection heuristic; well-separated synthetic clusters make connectivity problems starker than in real embeddings.
🐍 Exercise 2 (research): how do IVF, PQ and graph indexes trade recall for computation and memory, and why do graph indexes need long-range links?
Compare IVF, PQ with reranking and graph search on clustered vectors; measure recall@10 and distance computations.

Vector search in AI, robotics and aerospace

  • Document retrieval: RAG over millions of chunks of manuals, reports and standards.
  • Place recognition: robots match image descriptors against a map database with ANN search for loop closure.
  • Anomaly search: finding past telemetry windows similar to a current anomaly in a large archive.

References

  1. H. Jégou, M. Douze and C. Schmid (2011). “Product quantization for nearest neighbor search.” IEEE TPAMI.
  2. Y. A. Malkov and D. A. Yashunin (2018). “Efficient and robust approximate nearest neighbor search using hierarchical navigable small world graphs.” IEEE TPAMI.
  3. J. Johnson, M. Douze and H. Jégou (2019). “Billion-scale similarity search with GPUs.” IEEE Transactions on Big Data.
  4. S. J. Subramanya et al. (2019). “DiskANN: fast accurate billion-point nearest neighbor search on a single node.” NeurIPS.