Vector Databases

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.

Race three indexes to the 10 nearest

3

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

The Scan Problem

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.

Say it aloud

C equals n times d.

C
C the work for one query, counted in multiply-adds.
n
n the number of stored vectors: here 1,000,000.
×
times one full comparison for each stored vector.
d
d the dimension: how many numbers each vector holds, here 768.
In plain words

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.

With numbers

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.

Grow the collection until the scan breaks

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.

1M

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.

The road

  1. Exact search: cosine, dot product and distance, and when they agree.
  2. Recall@k: the one score that judges every shortcut.
  3. IVF: cut space into cells and open only a few.
  4. HNSW: a graph with express lanes on top.
  5. Product quantization: store 16 bytes where 3,072 were.
  6. The memory budget: combine the tricks and count every byte.
  7. Filters: "nearest, but only in stock".
  8. A living index: updates, deletes and drift.
  9. Showcase: race the indexes on your own data.
  10. Field guide: numbers, code and links.
A brute-force query over 1M vectors reads 3.07 GB. The collection grows to 2M vectors of the same size. What happens to the work per query?

Chapter 1

Exact Search and the Distance You Pick

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.

MeasureHow to compute itBest match
Dot productMultiply matching numbers, add themLargest
Cosine similarityThe dot product divided by both lengths: the cosine of the angleLargest, at most 1
L2 distanceThe straight-line distance between the two tipsSmallest

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.

Turn the query and compare three rankings

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.

Say it aloud

The squared length of q minus v equals two minus two times the cosine of q and v.

‖q − v‖2
the squared length of q minus v the squared L2 distance between the query q and the stored vector v.
2
two the squared length of q plus the squared length of v: 1 + 1.
cos(q, v)
the cosine of q and v the cosine similarity, from −1 to 1. For length-1 vectors it equals the dot product.
In plain words

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.

With numbers

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.

Two length-1 vectors have cosine similarity 0.9. What is their squared L2 distance?

Chapter 2

Recall at k: The Score for Every Shortcut

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.

Say it aloud

Recall at k equals the count of A intersect G, over k.

recall@k
recall at k the share of the true k nearest that the index found, from 0 to 1.
A
A the set of k ids the index returned.
∩
intersect keep only the ids that are in both sets.
G
G the ground truth: the true k nearest ids, from brute force.
| |
the count of how many ids the set holds.
|
closing bar ends the count.
k
k how many results you asked for, here 10.
In plain words

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 numbers

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.

Add error and watch recall fall

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.

30%

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.

An index returns 10 results. Seven are in the true top 10, and three are close but not in it. What is recall@10?

Chapter 3

IVF: Cluster First, Search a Few Cells

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.

  1. Build. Run k-means on the vectors to find nlist centres, the centroids. Each vector joins the list of its nearest centroid. The region a centroid owns is its cell.
  2. Query. Compare the query with all nlist centroids. Open the nprobe nearest cells.
  3. Scan. Compare the query with every vector in the open cells. Return the best k.

Open more cells and count what it costs

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.

1

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.

Say it aloud

C-IVF equals n-list times d, plus n-probe over n-list, times n times d.

CIVF
C-IVF the multiply-adds for one IVF query.
nlist × d
n-list times d the cost of comparing the query with every centroid.
nprobe / nlist
n-probe over n-list the share of all cells you open, so the share of vectors you scan.
n × d
n times d the full brute-force cost from Chapter 0.
In plain words

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.

With numbers

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.

1M vectors, nlist = 1,000 cells of equal size, nprobe = 100. About how many stored vectors does one query compare against?

Chapter 4

HNSW: A Graph With Express Lanes

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.

  1. Graph. Each vector is a node. Each node links to about M nearby nodes. Layer 0 holds every node, with up to 2M links each.
  2. Layers. Each node also gets a random top layer. Few nodes reach layer 1, fewer reach layer 2. Upper layers have long links: the highways.
  3. Search. Start at the entry node on the top layer. Move to whichever neighbour is closer to the query, until none is. Drop a layer and repeat. On layer 0, keep a list of the efSearch best nodes so far, and return the best k.

Walk the layers down to the query

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.

20

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.

Say it aloud

Level equals the floor of minus the log of U, times m-L.

level
level the highest layer this node joins; it joins every layer below too.
⌊ ⌋
the floor of round down to a whole number.
⌋
close the floor ends the rounding.
−ln(U)
minus the log of U U is a uniform random number from 0 to 1; minus its natural log is usually small and rarely large.
mL
m-L the level scale, 1/ln(M): 0.361 for M = 16.
In plain words

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.

With numbers

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.

With M = 16 and 1M vectors, about how many nodes reach layer 2 or higher?

Chapter 5

Product Quantization: Shrink Every Vector

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.

  1. Split. Cut each d-number vector into m pieces of d/m numbers.
  2. Train. For each piece position, run k-means with K = 256 centres. The centres are that piece's codebook; each centre is a codeword.
  3. Encode. Replace each piece by the number of its nearest codeword, 0 to 255: one byte. A vector becomes m bytes, its code.

Snap pieces to codewords

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.

16

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).

Say it aloud

D-tilde of q and x equals the sum over j of T-j at c-j of x.

d̃(q, x)
d-tilde of q and x the estimated squared distance from the query q to stored vector x.
Σj
the sum over j add one term for each of the m pieces.
Tj
T-j the table for piece j: K squared distances, built once per query.
cj(x)
c-j of x the byte stored for x in piece j: which codeword its piece snapped to.
In plain words

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 numbers

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.

PQ with m = 16 pieces and 8 bits per piece. How many bytes does each compressed vector take?

Chapter 6

Composite Indexes and the Memory Budget

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:

StringReads as
FlatBrute force over full vectors
HNSW32HNSW with M = 32 over full vectors
IVF4096,Flat4,096 cells, full vectors inside
IVF4096,PQ164,096 cells, 16-byte PQ codes inside
IVF4096,PQ16,RFlatThe 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.

Say it aloud

RAM equals n times, b-code plus b-link plus b-id, plus b-fixed.

RAM
RAM the memory the index needs, in bytes.
n
n the number of stored vectors.
bcode
b-code bytes for one vector's content: 4 × d for floats, m for PQ.
blink
b-link bytes for one node's graph links; FAISS gives M × 2 × 4 for HNSW, 0 for IVF.
bid
b-id bytes for the stored id: 8 in FAISS IVF lists, 0 where the position is the id.
bfixed
b-fixed shared parts paid once: centroids and codebooks.
In plain words

Add b-code, b-link and b-id to get the bytes for one vector. Multiply by n. Add b-fixed once.

With numbers

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.

Fit five indexes into your RAM

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.

10M
64 GB

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.

What does the FAISS string IVF4096,PQ16 describe?

Chapter 7

The Database Layer: Filters and Hybrid Search

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′.

Say it aloud

K-prime equals k over s.

k′
k-prime the candidates to fetch from the index before the filter.
k
k the results you want after the filter, here 10.
s
s the selectivity: the share of items that pass, from 0 to 1.
In plain words

On average only a share s of the candidates pass. To keep k of them, fetch k divided by s.

With numbers

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%.

Filter after the search and count what is left

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.

5%
100

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.

You want 10 results. Only 0.1% of items pass the filter. A post-filter fetches 1,000 candidates. What happens?

Chapter 8

A Living Index: Updates, Deletes and Drift

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.

Deletes

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

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.

Pour in new data, then retrain

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:

  1. Keep a fixed set of test queries, refreshed with real recent queries, and their brute-force ground truth.
  2. After every batch of inserts, measure recall@k and the work per query.
  3. If recall falls or work rises past a limit, retrain the centroids or rebuild offline, then swap the new index in.

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.

Your IVF index was trained when 80% of items were electronics. A year later, 60% of new items are clothing. What is the likely effect?

Chapter 9

Showcase: Race the Indexes

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.

Sweep both indexes on one dataset

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

Field Guide

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.

TermRule or numberUse it for
Brute forcen × d multiply-adds; 3.07 GB read for 1M × 768 floatsGround truth, small collections
Cosine vs L2Squared distance = 2 − 2 cos, for length-1 vectorsNormalize once, any measure ranks the same
Recall@kShared ids over k, averaged over test queriesEvery tuning decision
IVFnlist × d + (nprobe/nlist) × n × d; FAISS: nlist 4√n to 16√nLow memory per vector, fast build
HNSWLevel = floor(−ln U × 1/ln M); 1/M of nodes per next layerHigh recall at low work, enough RAM
PQm bytes per vector; m = 16 is 192× smaller than 768 floatsBillions of vectors, with refinement
Memoryn × (code + links + id) + fixedPick the index before you build
Post-filterFetch k/s candidates, and more for safetyLoose filters

Checklist before you ship

  1. Normalize vectors if the model expects cosine; check the lengths.
  2. Build ground truth for 1,000 test queries with brute force.
  3. Sweep the search knob; pick the cheapest setting that clears your recall line.
  4. Compute memory with the formula; plan for two years of growth.
  5. Measure the selectivity of real filters; choose pre-, post- or exact-scan per query.
  6. Re-measure recall and cell sizes after every big batch; retrain on drift.
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))

Where real systems sit

SystemWhat its docs say
FAISSA library of indexes (Flat, IVF, HNSW, PQ and combinations) built from factory strings; no server, no metadata.
pgvectorPostgres 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.
QdrantHNSW (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.
MilvusMany index types for float vectors, including FLAT, IVF_FLAT, IVF_PQ, HNSW and DISKANN.

Keep going

LessonWhat it adds
Vector EmbeddingsWhere the vectors come from
Similarity MetricsMore distance measures, in depth
K-MeansThe clustering behind IVF and PQ
Text ChunkingWhat goes into each vector
RAGVector search feeding a language model
Multimodal RAGImages and text in one index
Embedding OpsRunning embeddings in production
Embedding BenchmarksChoosing the model before the index

Sources

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).

The takeaway. Pick the recall you need, then buy it with the least work and memory. Measure recall against brute force; never trust a default.
You have 200M vectors of 768 floats and 128 GB of RAM. You need recall@10 near 0.95. Which plan fits?

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.

Vector Databases
Back to Gleams