Courses / RAG Systems / Module 5
Module 5: Vector databases and indexing: HNSW, IVF, quantization, metadata filters
12 h · theory 4 · hands-on 5 · project 2 · revision 1
You will be able to
- Explain HNSW and IVF and tune them for recall vs latency
- Use scalar and binary quantization and measure the loss
- Filter by metadata without wrecking recall
- Choose between Qdrant, pgvector and a managed service
Capstone increment: Qdrant (or pgvector) index with metadata filters, tuned and benchmarked.
Job-description skills: Vector databases · Lab tools: qdrant-client, pgvector, psycopg
1. Exact search doesn’t scale; approximate search trades recall for speed
Brute-force search compares the query with every vector: perfect recall, but cost grows with the corpus. Approximate nearest-neighbour (ANN) indexes compare the query with a small, well-chosen subset and accept that they will sometimes miss a true neighbour. Every index exposes a knob that trades recall for latency, and your job is to set it from measurements.
The picture below is an IVF index in two dimensions. Click to move the query and change how many cells are searched. Watch recall and the number of distance computations move together.
Recall@10 30% · returned 10 of 10 · distance computations 36 vs 400 for brute force (9%)
Guided experiments
- 16 cells, nprobe 1, query in the middle. What is recall? Raise nprobe one step at a time. When does recall reach 100%, and what fraction of the index are you scanning then?
- Move the query onto the border between two clusters. Why does a border query need a higher nprobe than one in the centre of a cell?
- Set nlist to 32 with nprobe 1, then nlist 4 with nprobe 1. Which scans less? Which has better recall? This is the knob HNSW’s ef_search plays in a graph index.
- Turn on “Filter after search”. Why does tenant A get almost nothing back? Now try “Filter during search”, and see why you may also need a higher nprobe for rare tenants.
2. HNSW: a graph you can walk
Hierarchical Navigable Small World (HNSW) graphs link each vector to its near neighbours in several layers, sparse at the top and dense at the bottom. A search enters at the top, greedily walks towards the query, and drops a layer each time it can get no closer. It is the default index in Qdrant, pgvector, Weaviate, Milvus and most others.
Three parameters matter. M is the number of links per node (more links: better recall, more memory). ef_construction is how hard the build searches for good links. ef_search is how many candidates a query keeps while walking; raise it for recall, lower it for speed. HNSW handles inserts well, but deletes are usually marked rather than removed, so heavy churn needs periodic rebuilds or optimisation.
Deep dive
Deep dive: an HNSW search, hop by hop
HNSW builds a graph in which each vector links to about M near neighbours, in several layers like a skip list. Every vector is on layer 0; each layer up keeps a random fraction of about 1/M of the vectors below it (levels are drawn with mL = 1/ln M), so the top layer has a handful of nodes with long links.
A search starts at the entry point on the top layer and moves greedily to whichever neighbour is closer to the query, until no neighbour is closer. Then it drops a layer and repeats. On layer 0 it switches to a best-first search that keeps a list of the ef best candidates seen so far, and returns the top k of them.
- Top layer: from the entry point, hop to a closer neighbour while one exists (a few long hops).
- Each lower layer: start where the layer above stopped and hop greedily again (shorter hops).
- Layer 0: best-first search. Keep ef candidates, expand the closest one not yet expanded, and stop when it is farther than the worst of the ef kept.
- Return the k closest of the ef candidates. A larger ef means more distance computations and higher recall.
Worked example: memory and work for 10 million 768-d vectors with M = 16
vectors: 10M × 768 × 4 bytes = 30.7 GB graph links: 10M × 32 links (layer 0) × 4 B ≈ 1.3 GB, upper layers add ~1/16 more brute force: 10 million distance computations per query HNSW, ef 100: a few thousand distance computations, recall@10 often ≥ 0.95 ef_search changes at query time; M and ef_construction need a rebuild
This query: recall@10 70% · distance computations 44 of 400 · hops on upper layers 6
Average over 40 queries: recall@10 96% · 45 distance computations · layers 4, nodes per layer 400 / 48 / 7 / 1
Guided experiments
- Draw layer 3 (the top). How many nodes live there, and how long are the links? Now draw layer 0. Why does a skip-list-like hierarchy let a search cross the space in a few hops?
- M = 8, ef_search 10, then 40 and 80. Watch the average recall and the distance computations. This is the recall-for-speed knob you tune at query time, with no re-indexing.
- Set M = 2 and push ef_search to 80. It still can’t match what M = 8 reaches at ef_search 40, while costing more comparisons. Why can’t search fully make up for a graph that is too sparse? M and ef_construction are build-time choices: changing them means rebuilding the index.
- At 400 points the savings look small. At 50 million vectors, brute force is 50 million comparisons per query while HNSW needs a few thousand. What does that cost in memory (hint: M links per node per layer)?
3. IVF and quantization
IVF (inverted file) indexes cluster vectors with k-means into nlist cells and search only the nprobe cells nearest the query. They build fast and use little memory, which is why FAISS and pgvector’s IVFFlat use them at large scale, but recall drops for queries near cell borders unless nprobe is raised.
Quantization shrinks each vector. Scalar quantization stores each dimension as an 8-bit integer (4× smaller than float32). Binary quantization keeps one bit per dimension (32× smaller) and compares with Hamming distance. Product quantization splits vectors into sub-vectors and stores a code per piece. The trick that makes aggressive quantization usable is rescoring: fetch several times more candidates with the small codes, then re-rank them with the original vectors, which can live on disk.
Deep dive
Deep dive: product quantization in numbers
Product quantization (PQ) cuts each vector into m sub-vectors and replaces each one with the ID of its nearest centroid in a small codebook learned with k-means, usually 256 centroids, so one byte per sub-vector. A 768-d float vector (3,072 bytes) with m = 96 becomes 96 bytes.
Distances are computed without decompressing. For each query, precompute the distance from each query sub-vector to all 256 centroids of its codebook, a 96 × 256 table. The distance to any stored vector is then the sum of 96 table look-ups. That is why IVF-PQ can scan millions of codes per second, and why it needs a final re-ranking with full vectors to get the order exactly right.
Worked example: PQ for 768-d vectors with m = 96
768 dims ÷ 96 sub-vectors = 8 dims each codebook per sub-vector = 256 centroids × 8 dims, learned with k-means stored code = 96 sub-vectors × 1 byte = 96 bytes (vs 3,072: 32× smaller) query time = build a 96 × 256 table of sub-distances once distance to one stored vector = 96 table look-ups + 95 additions 10M vectors = 30.7 GB as float32 → 0.96 GB as PQ codes
4. Filter without wrecking recall
Real queries come with filters: this tenant, these document types, newer than 2024, readable by this user. If you search first and filter the top 10 afterwards, a rare filter value leaves you with almost nothing; try the tenant filter in the picture above. The index has to apply the filter during the search.
Qdrant builds payload indexes and keeps its HNSW graph navigable under filters. pgvector 0.8 added iterative index scans that keep searching until enough rows pass the WHERE clause. For a handful of very large tenants, separate collections or partitions are simpler and faster. Always index the fields you filter on.
5. Qdrant, pgvector or a managed service?
Choose pgvector when you already run Postgres, the corpus is up to the low tens of millions of vectors, and you want vectors, metadata and access lists in one transactional database with joins. Choose Qdrant (or a similar dedicated engine) for heavy filtering, quantization with rescoring, sparse and dense vectors together, and horizontal scale. Choose a managed service when the team can’t run infrastructure and the bill is acceptable.
Decide with a benchmark on your data, not the vendor’s: recall@10 against brute force, p50 and p95 latency at your expected queries per second, memory per million vectors, ingest rate and how filters behave. ann-benchmarks shows how the algorithms compare in general; your benchmark shows what you will live with.
Hands-on: coding window
The coding window and the full VS Code lab are available after you sign in.
Sign in to codeLabs
Lab 5.1: Tune HNSW in Qdrant
Run Qdrant in Docker, index the capstone chunks, and measure recall@10 against exact search and p95 latency for ef_search 16, 64 and 256 with m 16 and 32.
Expected: A table of recall and latency per setting, and the setting you choose with a reason.
Lab 5.2: Quantization
Turn on scalar and then binary quantization with oversampling 2× and 4× and rescoring. Record memory use, recall@10 and latency for each.
Expected: A results table and a note on where the originals are stored.
Lab 5.3: Filtered index (capstone increment)
Add payload indexes for tenant, doc_type and year, run filtered queries for a rare tenant, and write a benchmark report in docs/benchmarks/index.md.
Expected: Filtered queries return k results with recall within 2 points of unfiltered search.
Go deeper
Videos
- HNSW for Vector Search Explained and Implemented with Faiss (Python) · James Briggs · ~35 min. HNSW explained from the ground up and built with FAISS, including the effect of each parameter.
- What is a Vector Database? Powering Semantic Search & AI Applications · IBM Technology · ~10 min. A clear ten-minute overview of what a vector database adds beyond an index.
- Product quantization in Faiss and from scratch · mildlyoverfitted · ~25 min. Product quantization implemented from scratch and compared with FAISS.
- Vector Database Search - Hierarchical Navigable Small Worlds (HNSW) Explained · DataMListic · ~8 min. A short visual explanation of the layered graph and the greedy search.
- Vector Database Search: HNSW Algorithm Explained · Redis · ~13 min. HNSW from a vector database team, including the parameters you tune in production.
Further reading
- Paper Efficient and robust approximate nearest neighbor search using Hierarchical Navigable Small World graphs · Malkov and Yashunin, 2016. The HNSW paper. Algorithms 1, 2, 4 and 5 are the insert, layer search, neighbour-selection and k-NN search steps the tool runs.
- Course Faiss: The Missing Manual · Pinecone. Free chapters on IVF, product quantization, HNSW and composite indexes, with code.
- Docs Faiss wiki · Meta AI. Index types, the index factory strings and guidance on picking an index for your size.
- Docs Indexing · Qdrant docs. HNSW parameters, payload indexes and how filtering interacts with the graph.
- Article Filterable HNSW · Qdrant. Why filtering breaks graph search and how adding links for filter values fixes it.
- Interactive ANN-Benchmarks · Aumüller, Bernhardsson and Faithfull. Recall-versus-queries-per-second curves for every major index; see the trade-off on real data.
GitHub repositories
- qdrant/qdrant: docs on indexing and quantization: payload indexes, HNSW config, scalar and binary quantization with rescore.
- pgvector/pgvector: The README sections on HNSW, IVFFlat, iterative index scans and half-precision and binary vectors.
- facebookresearch/faiss: The wiki pages on index types (IVF, PQ, HNSW) and the guidelines for choosing an index.
- erikbern/ann-benchmarks: How recall-versus-queries-per-second plots are produced; reuse the method for your own benchmark.
Checkpoint quiz
Interview questions
- Explain HNSW to a backend engineer. What do M and ef_search trade off?
- How would you benchmark a vector database for your workload?
- You need to filter by tenant and permissions. How do you keep recall high?
- When would you choose pgvector over Qdrant, and the other way round?
- How do you size memory for 50 million 1,024-dimension vectors? What can you do to cut it?
Ask the professor
Sign in to ask questions about this module.
Discussion
Community discussion appears here once giscus is configured (see README).