Brute force computes 1,500 distances to find the 10 nearest points. A graph index finds the same 10 after about 100. A vector database is the art of that skip.
Pick an index, then drag Search effort. Tap the map to move the query. Watch how many points each index examines, and how many true neighbours it finds. Then we build, piece by piece, the scan, the recall score, IVF, HNSW, product quantization, filters and upkeep.
You need a little Python and what a vector is (a list of numbers). It helps to have met Vector Embeddings. We build the rest from zero.
A live toy: 1,500 points in 2-D, k = 10. IVF has 32 cells and effort sets how many it opens (1 to 16). HNSW has M = 8 and effort sets efSearch (10 to 80). The averages run over 150 random queries. Real embeddings have hundreds of dimensions, where search is harder.
Chapter 0
Count the work of comparing one query with every stored vector, and see why it breaks a 50 ms budget
You run a shop search. An embedding model (a network that turns text into a list of numbers) has turned one million product descriptions into vectors of 768 numbers each. A shopper types "warm waterproof boots". You embed the query the same way. Now you want the 10 stored vectors closest to it.
The plain method is brute force: compare the query with every stored vector, then keep the 10 best. It is exact. It is also slow, because the work grows with every vector you add.
How much work is one query? Call the number of stored vectors n and the number of numbers in each vector, its dimension, d. One comparison multiplies d pairs of numbers and adds them up. Call the total work for one query C.
C equals n times d.
Each comparison costs d multiply-adds. You do one comparison for each of the n vectors. So C is n times d, and it doubles when n doubles.
n = 1,000,000 and d = 768 give C = 768,000,000 multiply-adds per query. Each number is a 4-byte float, so the scan also reads 3.07 GB. At an assumed memory speed of 20 GB/s, reading alone takes about 154 ms.
Pink is the time to read every vector once. The dashed line is a 50 ms budget. Drag the collection size and pick a dimension.
Time is bytes read divided by an assumed 20 GB/s of memory speed, on one machine, float32 vectors. Real speed depends on hardware, batching and caches; the straight-line growth does not.
A vector database keeps a vector index: a structure built once that lets a query skip most comparisons. The price is that it may miss a few true neighbours. Search with this price is approximate nearest neighbour search, or ANN.
Failure. The symptom: search was fast at launch and gets slower every month. Measure query time against collection size; a straight rising line means a scan. Fix: add an index before n reaches the point where n × d bytes no longer fit your time budget.
Chapter 1
Rank vectors by dot product, cosine and distance, and see that normalizing makes all three agree
Before you skip work, decide what "closest" means. There are three common answers. Each one gives a different ranking unless you prepare the vectors.
| Measure | How to compute it | Best match |
|---|---|---|
| Dot product | Multiply matching numbers, add them | Largest |
| Cosine similarity | The dot product divided by both lengths: the cosine of the angle | Largest, at most 1 |
| L2 distance | The straight-line distance between the two tips | Smallest |
The dot product rewards long vectors. A long stored vector can win even if it points a little away from the query. Cosine ignores length and looks only at direction. Try it below.
Drag on the circle to turn the warm query arrow. The three columns rank the six stored vectors. Then press Normalize.
Illustrative 2-D vectors. The query has length 1. Vector B is long on purpose.
If you scale every vector to length 1, the rankings agree. Here is why. Call the query q and a stored vector v, both of length 1. The squared L2 distance and the cosine are then tied by one rule.
The squared length of q minus v equals two minus two times the cosine of q and v.
Take the cosine of q and v. Double it and subtract from 2. That is the squared distance. A larger cosine always gives a smaller distance, so both pick the same nearest v.
q = (0.6, 0.8) and v = (1, 0). The cosine is 0.6 × 1 + 0.8 × 0 = 0.6. The formula gives 2 − 1.2 = 0.8. Directly: (0.6 − 1)2 + 0.82 = 0.16 + 0.64 = 0.8. They match.
So normalize once, at insert time and at query time. Then one index serves all three measures. Many embedding models already return length-1 vectors; check before you rely on it.
pythonimport numpy as np X = np.random.randn(100_000, 768).astype("float32") # n x d stored vectors X /= np.linalg.norm(X, axis=1, keepdims=True) # every row now has length 1 q = X[42] + 0.05 * np.random.randn(768).astype("float32") q /= np.linalg.norm(q) # the query too scores = X @ q # n dot products: the brute-force scan top10 = np.argpartition(-scores, 10)[:10] # the 10 largest, unordered top10 = top10[np.argsort(-scores[top10])] # sort only those 10
Failure. The symptom: the same few long documents top every search. Measure the vector lengths; a wide spread means the dot product rewards length. Fix: normalize, or use cosine, unless the model was trained for raw dot products.
Chapter 2
Compare an index's answer with the exact answer, and turn the overlap into one number
Every index in this lesson skips work and may miss neighbours. How many does it miss? You need the exact answer to compare with. Brute force gives it. Run it once, offline, on a set of test queries. The result is the ground truth.
Call the k results the index returns A. Call the true k nearest, from brute force, G. The score counts how many ids appear in both.
Recall at k equals the count of A intersect G, over k.
Put the k ids in A next to the k ids in G. Count the ids they share. Divide by k. Average that over many test queries.
With made-up numbers: k = 10, and the index returns 8 of the true 10. Recall@10 = 8/10 = 0.8. Over three queries with 8, 10 and 9 hits, the average is 27/30 = 0.9.
The top row is the ground truth G. The bottom row is what a sloppy index returns, A. Drag the error to blur its distances. Press New query to draw again.
Illustrative: 300 random 2-D points; the "index" ranks them by true distance plus random noise. The average runs over 200 queries.
Recall is half the score. The other half is the work: distances computed, or queries per second. Every index has a knob that trades one for the other. A useful report is a curve of recall against work, not one point. Chapter 9 draws that curve.
Failure. The symptom: users say search "got worse" and no metric moved. Measure recall@k on a fixed set of test queries with stored ground truth. Fix: run that check after every rebuild or parameter change, and alert on a drop.
Chapter 3
Cut the space into cells with k-means, open only the cells near the query, and pay for the neighbours across the border
A library does not search every shelf. It sorts books by topic and sends you to one aisle. The inverted file index, IVF, does the same with vectors.
Yellow crosses are centroids. Lit points are in the opened cells. Tap the map to move the query, near a border to see a miss. Then raise nprobe.
Live toy: 1,200 points in 2-D, k = 10, k-means with 12 iterations. The average recall and work run over 150 random queries.
What does one query cost? Call the number of cells nlist, the number opened nprobe, the vector count n and the dimension d. Assume the cells hold equal shares of the vectors. Call the work CIVF.
C-IVF equals n-list times d, plus n-probe over n-list, times n times d.
First pay nlist times d to rank the centroids. Then pay the brute-force cost n times d, shrunk by the share of cells you open, nprobe over nlist.
n = 1,000,000, d = 768, nlist = 1,000, nprobe = 100. Centroids: 1,000 × 768 = 768,000. Scan: 0.1 × 768,000,000 = 76,800,000. Total 77,568,000, about 9.9 times less work than brute force.
How many cells? The FAISS guidelines suggest nlist between 4√n and 16√n, so 4,000 to 16,000 cells for a million vectors. The pgvector docs suggest rows/1000 lists up to a million rows and probes near √lists as a start.
Failure. The symptom: some queries miss their obvious best match. Measure recall for queries near cell borders. Fix: raise nprobe until recall stops rising, and stop there, since each step costs a cell more of scanning.
Chapter 4
Link each vector to its near neighbours, stack sparse layers on top, and walk downhill from the top layer
Picture a city with local streets and a few highways. To cross town, you take a highway near your goal, then exit and walk the last blocks. HNSW (Hierarchical Navigable Small World, Malkov and Yashunin, 2016) builds that map for vectors.
Bigger dots live on higher layers. The thick path is the walk on the upper layers; blue dots are nodes measured on layer 0. Tap the map to move the query. Change M and efSearch.
Live toy: 1,200 points in 2-D, efConstruction = 40, plain nearest-neighbour link selection (the paper adds a smarter heuristic). Averages run over 150 random queries.
How does a node get its top layer? Draw a random number U between 0 and 1. Scale it by a factor mL that the paper sets to 1/ln(M). Call the node's top layer level.
Level equals the floor of minus the log of U, times m-L.
Draw U. Take minus its log, multiply by m-L and round down. The result is the node's level. Large results are rare, so high layers stay sparse.
M = 16, so m-L = 1/ln(16) = 0.361. Draw U = 0.01: −ln(0.01) = 4.605, times 0.361 is 1.66, so level 1. Draw U = 0.3: 1.204 × 0.361 = 0.43, so level 0.
This rule gives each node a chance of 1/M to reach each next layer. So with a million nodes and M = 16:
1,000,000 → 62,500 → 3,906 → 244 → 15 → about 1 (layers 0 to 5)
The top layer is near log base 16 of a million, which is 4.98. A walk needs a few hops per layer, so the work grows with the log of n, not with n.
Failure. The symptom: recall sits at 0.9 and will not rise. Measure recall as you raise efSearch; if it flattens, the graph lacks links. Fix: rebuild with a larger M or efConstruction. FAISS defaults are efConstruction 40 and efSearch 16; pgvector uses m 16, ef_construction 64 and ef_search 40.
Chapter 5
Cut each vector into pieces, store each piece as one byte, and score with table lookups
IVF and HNSW cut the number of comparisons. They do not cut memory. A million 768-dimension float vectors take 3.07 GB. A billion take 3 TB. Product quantization, PQ (Jégou, Douze and Schmid, 2011), stores each vector in a few bytes.
This is one piece position, drawn in 2-D. Each point snaps to its nearest yellow codeword; red lines are the error. Pick K. Drag m to size a full 768-dimension code.
The 2-D cloud is an illustrative toy of 400 points; error is the mean squared snap distance. The byte counts are exact for m codes of 8 bits.
How do you score a compressed vector without unpacking it? Before the scan, build one table per piece. Call the table for piece j Tj: it holds the squared distance from the query's piece j to each of the K codewords. Call the stored code of vector x in piece j cj(x). Call the estimated squared distance d̃(q, x).
D-tilde of q and x equals the sum over j of T-j at c-j of x.
For each piece j, read the byte c-j of x. Look up that entry in the table T-j. Add the m entries. The sum is d-tilde.
With made-up numbers and m = 2: x has codes 17 and 203. T-1 at 17 is 0.12 and T-2 at 203 is 0.30, so d-tilde is 0.42. At full size (m = 16, K = 256, d = 768), the tables cost 16 × 256 × 48 = 196,608 multiply-adds once. Each vector then costs 16 additions, not 768 multiply-adds.
Bytes per vector are m × 8 bits / 8 = m. So m = 16 stores 16 bytes where float32 stored 3,072: 192 times smaller. The distances are estimates, so PQ loses some recall. Chapter 6 shows how to win it back.
Failure. The symptom: recall stalls at a modest value whatever nprobe or efSearch you set. Measure recall of PQ against the same index with full vectors. Fix: raise m, or re-score the top candidates with full vectors.
Chapter 6
Stack IVF, HNSW and PQ, count every byte each one keeps, and fit the index to your RAM
The tricks combine. IVF-PQ opens a few cells with IVF, then scores their vectors from PQ codes. HNSW over PQ walks the graph with compressed vectors. Refinement takes the best few hundred PQ candidates and re-scores them with full vectors, often kept on disk. FAISS writes these as index factory strings:
| String | Reads as |
|---|---|
Flat | Brute force over full vectors |
HNSW32 | HNSW with M = 32 over full vectors |
IVF4096,Flat | 4,096 cells, full vectors inside |
IVF4096,PQ16 | 4,096 cells, 16-byte PQ codes inside |
IVF4096,PQ16,RFlat | The same, then re-score candidates with full vectors |
Which one fits? Count the bytes. Per vector, an index keeps a code of bcode bytes, graph links of blink bytes and an id of bid bytes. Shared parts, such as centroids and codebooks, take bfixed. With n vectors, call the total RAM.
RAM equals n times, b-code plus b-link plus b-id, plus b-fixed.
Add b-code, b-link and b-id to get the bytes for one vector. Multiply by n. Add b-fixed once.
IVF4096,PQ16 with n = 1,000,000 and d = 768: b-code 16, b-link 0, b-id 8, so 24 MB. Centroids are 4,096 × 768 × 4 = 12.6 MB and codebooks 0.8 MB. RAM is about 37 MB. HNSW32 needs 3,072 + 256 bytes per vector: 3.33 GB.
Each bar is one index's memory from the formula above, on a log scale. Red bars do not fit the dashed budget. Drag the collection size and the budget.
Formula sizes only: float32 vectors, nlist = 4,096, PQ m = 16, HNSW links from the FAISS guideline M × 2 × 4 bytes. RFlat keeps its full vectors on disk in this plan. Real systems add overhead.
Failure. The symptom: the index server is killed for using too much memory as the collection grows. Measure bytes per vector times n before you build. Fix: move from full vectors to PQ codes, and keep full vectors on disk for refinement.
IVF4096,PQ16 describe?Chapter 7
Ask for the nearest items that also pass a condition, and see why filtering after the search runs dry
A real query has conditions: "boots like this, in stock, under 100 dollars". The extra fields are metadata. A library such as FAISS gives you an index. A vector database adds what a database adds: storage on disk, updates, metadata, filters, an API and copies on several machines.
There are two plain ways to filter. A post-filter asks the index for some candidates, then drops those that fail the condition. A pre-filter keeps only the passing items, then searches among them. The share of items that pass is the selectivity.
How many candidates must a post-filter fetch? Call the results you want k, the selectivity s and the candidates to fetch k′.
K-prime equals k over s.
On average only a share s of the candidates pass. To keep k of them, fetch k divided by s.
k = 10 and s = 0.001 (one item in a thousand passes) give k-prime = 10,000. Fetch only 1,000 and you expect 1 result. Even 10,000 gives 10 or more only 54% of the time; 20,000 gives 99.5%.
Each square is one fetched candidate; green ones pass the filter. Drag the selectivity down and see the post-filter run dry. Then switch to pre-filter.
Each candidate passes with chance s, independently. The squares show one random draw; the chance of 10 or more results is exact, from the binomial distribution.
Real systems choose between the two per query. The pgvector docs warn that an approximate index applies the filter after the scan, so a query can return fewer rows. Version 0.8.0 adds iterative index scans that keep searching. Qdrant adds extra graph edges based on indexed payload values, and its planner switches to a full scan when few points match.
Hybrid search runs a keyword search, such as BM25, beside the vector search and merges the two ranked lists. A common merge is reciprocal rank fusion (Cormack et al., 2009). Each list gives an item 1/(60 + its rank). The item's score is the sum.
Failure. The symptom: filtered queries return 2 results when you asked for 10. Measure the selectivity of the filters your users send. Fix: pre-filter or use a filter-aware index for rare conditions, and fall back to an exact scan of the passing rows when they are few.
Chapter 8
Add data the index was not trained on, watch the cells swell, and measure recall to know when to rebuild
You train an index on the data you have on day one. Then the data changes. A shop adds a new category. A new embedding model ships. The index still answers, but it answers on old assumptions.
Removal is not free in every index. FAISS supports remove_ids on IndexFlat, IndexIVFFlat and IndexIDMap, and it makes a full pass, so batch removals. Its guidelines say HNSW does not support removing vectors. Databases often mark a deleted item as a tombstone (a flag that hides it from results) and clean up in a later rebuild.
Drift is a change in where new vectors land. IVF centroids came from the old data. New vectors in a new region all join the nearest old cell, which swells. Queries there scan a huge cell, or miss neighbours in cells that do not fit the data. The device below runs this on a real toy IVF.
We trained the index on the dim points at left. Press Add new data to pour bright points into a new region. Watch the list sizes and the cost of queries there. Then press Retrain.
Live toy: 16 cells, nprobe = 2, k = 10. "New-region queries" are 100 random queries drawn from the new data. Work counts the vectors scanned.
With made-up numbers: 16 cells of 50 vectors and nprobe = 2 scan about 100 vectors. If 600 new vectors join one old cell, that cell holds 650. A query there now scans about 700 vectors, seven times the work, for the same answer quality or worse.
The routine that catches this has three parts:
Failure. The symptom: latency creeps up and recall slips with no code change. Measure the size of the largest cells and recall on recent queries. Fix: retrain on a fresh sample, rebuild, and swap.
Chapter 9
Build IVF and HNSW on one dataset, sweep their knobs, and read the recall against the work
Every chapter gave one knob. Here they meet. Pick a dataset and press Build and sweep. The device builds both indexes, runs 100 test queries at each setting of nprobe and efSearch, and draws recall against the distances computed. Up and to the left is better.
Yellow dashes are IVF (its cells), teal is HNSW, pink is the scan. Each dot is one knob setting, averaged over 100 queries. Pick a dataset and a size, then build. Tap a dot to read its numbers.
Live toy in 2-D: IVF with nlist near 2√n, nprobe from 1 up; HNSW with M = 8, efConstruction = 40, efSearch from 10 to 160. Work is centroid plus vector distances for IVF, and all distances for HNSW. Rankings in 768 dimensions can differ.
Read the curves this way. Pick the recall you need, say 0.95. Find where each curve first crosses it. The one further left does less work for that recall. Then check the memory of that index in Chapter 6. The best index is the cheapest one that clears your recall line and fits your RAM.
Try the uniform dataset. IVF cells then have equal sizes and no natural borders, and both curves shift. Try 5,000 points. Brute force grows five times from 1,000; the HNSW work grows far less.
Chapter 10
Keep the numbers, the checklist and the code in one place
A vector database answers "which stored vectors are nearest" without a full scan. IVF opens a few cells. HNSW walks a layered graph. PQ shrinks each vector to a few bytes. Recall@k on a fixed test set tells you what each shortcut costs.
| Term | Rule or number | Use it for |
|---|---|---|
| Brute force | n × d multiply-adds; 3.07 GB read for 1M × 768 floats | Ground truth, small collections |
| Cosine vs L2 | Squared distance = 2 − 2 cos, for length-1 vectors | Normalize once, any measure ranks the same |
| Recall@k | Shared ids over k, averaged over test queries | Every tuning decision |
| IVF | nlist × d + (nprobe/nlist) × n × d; FAISS: nlist 4√n to 16√n | Low memory per vector, fast build |
| HNSW | Level = floor(−ln U × 1/ln M); 1/M of nodes per next layer | High recall at low work, enough RAM |
| PQ | m bytes per vector; m = 16 is 192× smaller than 768 floats | Billions of vectors, with refinement |
| Memory | n × (code + links + id) + fixed | Pick the index before you build |
| Post-filter | Fetch k/s candidates, and more for safety | Loose filters |
pythonimport faiss, numpy as np d, n = 768, 200_000 X = np.random.randn(n, d).astype("float32"); faiss.normalize_L2(X) Q = X[:1000] + 0.05 * np.random.randn(1000, d).astype("float32"); faiss.normalize_L2(Q) flat = faiss.IndexFlatL2(d); flat.add(X) _, G = flat.search(Q, 10) # ground truth: exact top 10 def recall(I, G, k=10): # shared ids over k, averaged return np.mean([len(set(a) & set(g)) / k for a, g in zip(I, G)]) ivf = faiss.index_factory(d, "IVF1024,PQ16") # 1,024 cells, 16-byte codes ivf.train(X); ivf.add(X) for p in [1, 8, 32, 128]: ivf.nprobe = p; _, I = ivf.search(Q, 10); print("nprobe", p, recall(I, G)) hnsw = faiss.IndexHNSWFlat(d, 32) # M = 32, no training hnsw.hnsw.efConstruction = 64; hnsw.add(X) for ef in [16, 64, 256]: hnsw.hnsw.efSearch = ef; _, I = hnsw.search(Q, 10); print("efSearch", ef, recall(I, G))
| System | What its docs say |
|---|---|
| FAISS | A library of indexes (Flat, IVF, HNSW, PQ and combinations) built from factory strings; no server, no metadata. |
| pgvector | Postgres extension with HNSW (defaults m 16, ef_construction 64, ef_search 40) and IVFFlat (default probes 1). Filters run after the index scan unless iterative scans are on. |
| Qdrant | HNSW (defaults m 16, ef_construct 100) with extra edges for indexed payload fields. Its planner falls back to a full scan for small filtered sets. |
| Milvus | Many index types for float vectors, including FLAT, IVF_FLAT, IVF_PQ, HNSW and DISKANN. |
| Lesson | What it adds |
|---|---|
| Vector Embeddings | Where the vectors come from |
| Similarity Metrics | More distance measures, in depth |
| K-Means | The clustering behind IVF and PQ |
| Text Chunking | What goes into each vector |
| RAG | Vector search feeding a language model |
| Multimodal RAG | Images and text in one index |
| Embedding Ops | Running embeddings in production |
| Embedding Benchmarks | Choosing the model before the index |
Malkov and Yashunin, Efficient and robust approximate nearest neighbor search using Hierarchical Navigable Small World graphs (2016). Jégou, Douze and Schmid, Product Quantization for Nearest Neighbor Search, IEEE TPAMI (2011). Douze et al., The Faiss library (2024), and the FAISS wiki pages Guidelines to choose an index and Special operations on indexes. The pgvector README. Qdrant, Indexing. Milvus, Index explained. Cormack, Clarke and Buettcher, Reciprocal Rank Fusion, SIGIR (2009).
Now press Present or Teach and explain from memory: why the scan breaks, what recall@k compares, how IVF and HNSW skip work, and how PQ scores with lookups. Then go back to the race and say why HNSW reached 10 of 10 with so few distances.