Approximate Indexes and Their Knobs
How HNSW graphs and IVF cluster indexes avoid scanning every vector, which settings are fixed at build time and which you can change per query, and what each one costs in recall, speed and memory.
Contentsand lesson path
On this page
- Why it matters
- Graph indexes: HNSW
- Cluster indexes: IVF
- Choosing an index, and where the knobs live
- Check your understanding
- Apply it
- Review prompt
Lessons of Vector Search Foundations
- Nearest-Neighbor Search Explained Concept · 15 min
- Brute-Force kNN as a Baseline Worked example · 20 min
- Approximate Indexes and Their Knobs Concept · 15 min
- Lab: HNSW Recall Versus Latency Lab · 25 min
- Filters and Hybrid Search with Rank Fusion Lab · 25 min
- Check: Pick an Index for a Workload Knowledge check · 6 questions
What you will learn
- Configure an approximate index (for example HNSW) and measure its recall against latency.
Prerequisites: Embeddings
01. Why it matters
Exact search does work proportional to the size of the collection for every query. An approximate index does most of its work once, at build time, organising the vectors so that a query only looks at a small, promising part of them. That is where the speed comes from, and also where the misses come from: a neighbour outside the explored part is never found.
Every approximate index has a few settings that decide how much it explores. Some are fixed at build time; others can change per query. Library defaults suit benchmark data, not necessarily yours, and the same setting gives different recall on different collections. To tune an index you need to know which knob trades what, so you can measure the right ones in the next lab.
02. Graph indexes: HNSW
HNSW (Hierarchical Navigable Small World, Malkov and Yashunin) is the default index type in most vector databases. It is a graph in which every vector is a node linked to some of its near neighbours.
- Layers. Every node lives on the bottom layer, and each also gets a random top layer, with each higher layer holding far fewer nodes, like an express line that stops only at major stations. Upper layers cross the space in long hops; the bottom layer has short, dense links.
- Search. A query starts at an entry point on the top layer and keeps moving to whichever linked node is closer to it until no link improves, then drops a layer. On the bottom layer it runs a wider best-first search that keeps a list of the best candidates seen so far and stops when no unexplored candidate can improve the list. The best
kon the list are the answer. - Insertion. Adding a vector is itself a search: the index finds the new node's neighbours on each of its layers and links them.
Three settings control it:
- M (build time): the links each node keeps per layer; the bottom layer allows twice as many in hnswlib and FAISS. More links make the graph easier to navigate, especially in high dimensions, but cost memory and build time. Values from 8 to 64 are common, 16 a frequent default.
- ef_construction (build time): how many candidates insertion considers when choosing links. Higher values build a better graph, more slowly, at no memory cost.
- ef, called
efSearchin FAISS (query time): the length of the candidate list on the bottom layer, and the main dial between recall and latency. You can change it per query without touching the graph. Keep it at leastk: FAISS and hnswlib quietly raise it tok, but pgvector returns at mosthnsw.ef_searchrows.
Memory is the vectors plus the links. The FAISS guidelines give d × 4 + M × 2 × 4 bytes per vector for its flat HNSW index: for 384 dimensions and M = 16 that is 1,536 bytes of vector and 128 bytes of links. Unless the vectors are small, the vectors dominate.
Other properties matter in production. HNSW accepts new vectors at any time without retraining, which suits a growing collection. Deleting is harder: many implementations only mark nodes as deleted and clean up later, and the FAISS HNSW index cannot remove vectors at all. Search speed relies on the graph sitting in RAM. And building is the slow part, since every insertion runs a search.
03. Cluster indexes: IVF
An inverted-file (IVF) index splits the space into regions. Training runs k-means on a sample of the vectors to find nlist centroids, and each vector is filed in the list of its nearest centroid. A query is compared with all centroids, and only the nprobe closest lists are scanned in full.
- nlist (build time): the number of lists. More lists make each probe cheaper but spread a query's true neighbours over more lists. pgvector suggests about
rows / 1000lists up to a million rows andsqrt(rows)beyond; the FAISS guidelines, written for larger collections, suggest 4 to 16 timessqrt(N). - nprobe (query time): how many lists to scan, the IVF equivalent of
ef.
Because the centroids are learned, IVF needs representative data before it is built, and it goes stale if the data shifts: new kinds of vectors are filed under centroids that fit them poorly, and recall drops until you retrain. In return its overhead is small. IVF is also the usual base for product quantisation (IVF-PQ), which stores each vector as a few bytes of codes, cutting memory sharply at a cost in accuracy that is often repaired by re-scoring the top candidates with full vectors.
import faiss
from knn import exact_knn
from vectors import make_dataset
docs, queries = make_dataset(n_docs=10_000, n_queries=200)
gt_ids, _ = exact_knn(docs, queries, k=10)
nlist = 100 # number of clusters (lists)
quantizer = faiss.IndexFlatIP(docs.shape[1]) # holds the cluster centroids
ivf = faiss.IndexIVFFlat(quantizer, docs.shape[1], nlist, faiss.METRIC_INNER_PRODUCT)
ivf.train(docs) # k-means: learn the centroids
ivf.add(docs) # file each vector under one list
for nprobe in (1, 4, 16, 64):
ivf.nprobe = nprobe # lists to scan per query
_, found = ivf.search(queries, 10)
hits = sum(len(set(f) & set(t)) for f, t in zip(found, gt_ids))
print(f"nprobe={nprobe:>2} scans ~{nprobe / nlist:4.0%} of vectors "
f"recall@10={hits / gt_ids.size:.3f}")nprobe= 1 scans ~ 1% of vectors recall@10=0.169
nprobe= 4 scans ~ 4% of vectors recall@10=0.428
nprobe=16 scans ~ 16% of vectors recall@10=0.766
nprobe=64 scans ~ 64% of vectors recall@10=0.993The shape is the general one: recall climbs as the query explores more, with diminishing returns. The numbers are specific to this data. The synthetic vectors from lesson 2 have no natural clusters, which is a hard case for IVF, so it needs to scan most of the lists for high recall; real embedding collections usually cluster more and reach the same recall with a much smaller share. The scans column is also only approximate, since k-means lists are rarely equally long. Never copy a setting from a benchmark run on other data; measure on your own vectors.
04. Choosing an index, and where the knobs live
A rough guide, to be confirmed by measurement:
- Exact (flat) search for collections that are small for your latency budget, for occasional queries, for small filtered subsets, and always as the reference for recall.
- HNSW when you need low latency at high recall, the vectors fit in RAM, and the collection grows continuously.
- IVF, often with quantisation, when the collection is very large or memory is tight, and the data is stable enough to train on.
The same knobs appear under different names. These are the ones you will meet most, with their defaults where the library sets one:
HNSW links per node build breadth search breadth
FAISS M (required) efConstruction (40) efSearch (16)
hnswlib M (16) ef_construction (200) ef (10)
pgvector m (16) ef_construction (64) hnsw.ef_search (40)
Qdrant m (16) ef_construct (100) hnsw_ef (= ef_construct)
IVF lists search breadth
FAISS nlist (required) nprobe (1)
pgvector ivfflat lists ivfflat.probes (1)Some defaults deserve suspicion. An IVF search that probes a single list is fast but often misses many neighbours, and the low default search breadths in FAISS (16) and hnswlib (10) favour speed over recall. In every library, the build-time settings need a rebuild to change, so try them on a sample before indexing millions of vectors, and keep the query-time setting in configuration so it can be tuned without a deploy.
05. Check your understanding
06. Apply it
Plan the measurements for the practice project before you run them:
- Choose the approximate index you will use: FAISS HNSW (used in the next lab), pgvector with an
hnswindex, or a vector database. Write down its build-time and query-time settings and their defaults. - Pick three settings to compare. A good start is one query-time setting at three values, such as search breadth 16, 64 and 256 with M = 16.
- Predict, before measuring, how recall@10 and latency will move across the three, and estimate the index memory with the formula above.
- Write down a recall target (for example 0.95 recall@10 against your exact baseline) and the latency budget from lesson 1. The lab will tell you which setting meets both.
07. Review prompt
Without looking back:
- Describe how an HNSW query moves from the entry point to its answer, and what the candidate list on the bottom layer is for.
- Name the three HNSW settings and say for each whether changing it needs a rebuild.
- Explain the IVF train, add and search steps, and why an IVF index can go stale.
- Estimate the memory of an HNSW index over 2 million vectors of 1,024 dimensions with M = 16.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.