Vector indexes from the inside: flat, IVF, PQ, HNSW, DiskANN, filtered search

How an index finds the nearest vectors without comparing the query with every one: exact search, k-means cells (IVF), product and scalar quantization, HNSW read in hnswlib and FAISS, Vamana (DiskANN), ScaNN, filters, deletes, memory and scale. Measured on the topic's real vectors (SciFact, NFCorpus, HotpotQA, QASPER with Qwen3-Embedding; 522,931 Quora questions for scale) on an Apple M1 Pro; published results kept apart. A child of Topic: rag-and-retrieval. Data as of October 2026. Reading: 39 min, plus 15 in closed details.

The idea in one screen

Exact search reads every stored vector for every query; an index answers the same question by reading less: only a few k-means cells (IVF), only the nodes a graph walk passes (HNSW, Vamana), or everything but in a few bytes each, then a short list rescored exactly (PQ, int8, RaBitQ). What it gives up is recall against exact search, and it pays in memory and build and update cost.

Four ways to read less, on the same query

  1. Exact: read everything. The query (orange post) is compared with every stored point; the five true nearest are ringed green. On SciFact that is 5,183 distances over 21 MB for every query, and recall 1.000 by definition.
  2. IVF: read the nearest cells. k-means has split the points into cells (walls on the floor, centroids as posts). The query is compared with the centroids, then scans only the nearest cell; a true neighbour just across a wall is missed (orange ring). Measured on SciFact: 72 cells, 8 probed, 696 distances, recall 0.901.
  3. Graph: read what the walk passes. Every point links to a few near ones. From an entry point the walk keeps moving to whichever neighbour is closer to the query and stops when none is; only the lit points are read. Measured: HNSW M 16, ef 40, 617 distances in 47 hops, recall 0.991.
  4. Codes: read everything, but small. Every vector is kept as a few bytes (flat chips); their approximate scores pick a shortlist of 10 (raised), which is rescored with the full vectors. Measured: 5,183 PQ codes of 16 B (83 KB), best 100 rescored, recall 0.914.

Points illustrative (one seeded set, distances on the floor); numbers measured here on SciFact, recall@10 against exact search.

You need: what an embedding is and why nearness means relevance (Embedding models), and where the index sits in retrieval (Topic: rag-and-retrieval, its Tool map tab; the pipeline around it is The retrieval pipeline). Indexes inside a database (pgvector's HNSW and IVFFlat in PostgreSQL, WAL, VACUUM, iterative scans, hybrid search) are Search and vector databases, measured on the same 522,931 Quora vectors used here for scale; tenants, access control and re-indexing are RAG in production.

ANN recall@k
share of the exact top k (by a flat scan) that the index returns; not relevance.
Distances per query
the work counted first on this page: deterministic, machine-independent.
IVF: nlist, nprobe
k-means cells; cells scanned per query.
PQ: m, codebook, ADC
m one-byte sub-vector ids; 256 learned centroids per sub-vector; scoring by table look-ups.
Rescoring
re-ranking a short list of candidates with the full vectors.
HNSW: M, efConstruction, ef
links per node; candidate list while building; candidate list while searching.
Vamana, α
DiskANN's single-layer graph; its pruning margin.
Selectivity
share of rows that pass a filter.
Tombstone
a deleted node left in the graph so routes through it still work.

Labels. measured here: run on an Apple M1 Pro (10 CPU cores, 16 GB), deterministic unless it says timed; timed runs use one CPU thread, one query at a time, so ratios between indexes transfer to servers better than milliseconds. published: a paper's or vendor's number, dated and labelled. Vectors: SciFact's 5,183 abstracts and 300 test claims, the four collections stacked (25,039), all from Qwen3-Embedding-0.6B (1,024 dimensions, unit length, so inner product = cosine), and BEIR Quora (522,931 questions, all-MiniLM-L6-v2, 384 dimensions).

How the timed runs were made (provenance)

Timed runs held the shared bench lock and record the load average beside each result; the parent page's running example supplies the vectors and the test claims.

1. The job, and the scorecard

k-nearest-neighbour search (kNN): given a query q and N stored vectors, return the k most similar. With unit-length vectors, cosine, inner product and Euclidean distance rank in the same order (|a − b|2 = 2 − 2 a·b), which is why every index here uses inner product; on unnormalised vectors inner product favours long vectors, so build with the metric the model was trained for. Approximate nearest neighbour search (ANN) accepts some wrong members of the top k for far less work. Its score, ANN recall@k, is the share of the true top k (from exact search on the same vectors) that the index returns, averaged over queries. It is not the parent page's retrieval recall against human labels; it only measures how faithfully the index imitates exact search, and it is always quoted with a cost, because any index is fast at low recall.

Predict: an index that returns 90% of the exact top 10 on SciFact. How much of exact search's nDCG@10 (answer quality against human labels) does it keep?

So chasing ANN recall from 0.99 to 0.999 is usually wasted latency for retrieval-augmented generation, where a reranker and a language model sit downstream; measure relevance on your own labelled queries before buying the last points. The reverse is dangerous: some defaults land far lower (the parent's Tool map: LanceDB's default IVF-PQ 0.59, FAISS IVF at nprobe 1 0.42, SciFact with bge-small). To measure recall yourself: compute a few hundred real queries' exact top k once with a flat scan, and compare every setting against it.

The last points of recall barely move answer quality; below 0.8 it falls

2. Exact search, and why it stops scaling

Exact search (flat, brute force) computes the similarity of the query with every stored vector and keeps the k best in a small heap. One query against the 5,183 SciFact vectors is 5.3 million multiply-adds over 21 MB. A core multiplies far faster than memory delivers numbers, so one query at a time is memory-bound: its speed is the speed of reading the vectors. FAISS's IndexFlatIP on one thread scanned at 37 GB/s once the collection no longer fitted in the caches measured here, timed.

work = N · d multiply-adds    bytes read = N · d · b
N
stored vectors
d
dimensions (1,024 for Qwen3-Embedding, 384 for MiniLM)
b
bytes per number: 4 for float32, 2 for float16, 1 for int8
Predict: one query, one CPU core, 1 million vectors of 1,024 float32 numbers (4.1 GB). How long does exact search take on this laptop?

Batching changes the bottleneck. With many queries at once, each vector read is reused for every query in the batch: the scan becomes a matrix multiplication (GEMM) that keeps the arithmetic busy. On the four corpora stacked (25,039 × 1,024): one query at a time 2.53 ms each; a batch of 200, 0.22 ms per query, about 12 times less measured here, timed. FAISS switches to BLAS only when queries × d reaches 128,000, so on Quora (384 dimensions) a batch of 200 is 76,800, it stayed on the one-at-a-time path, and the batch saved nothing (21 ms per query against 22 ms). So offline jobs (evaluating a golden set, deduplicating a corpus, building a kNN graph) often need no index, and GPUs do exact search well.

FAISS source: where the batch switches to BLAS; exact search on GPUs (code and depth)

Johnson, Douze and Jégou built a k-NN graph over 1 billion vectors in under 12 hours on 4 GPUs (arXiv 1702.08734, published, authors' runs, 2017).

faiss/utils/distances.cpp at v1.15.1, lines 572 to 577 and 607
if (res.sel || ny == 0 || nx * d < static_cast<size_t>(distance_compute_blas_threshold)) { exhaustive_inner_product_seq(x, y, d, nx, ny, res); // one query at a time } else { exhaustive_inner_product_blas(x, y, d, nx, ny, res); // a matrix multiplication } ... int distance_compute_blas_threshold = 128000; // nx * d: for d = 1,024, batches of 125+ queries

Exact search is the right answer for small collections (at 25,039 × 1,024 it costs 2.53 ms here; FAISS's decision tree says Flat below 10,000 vectors, ScaNN's docs "fewer than 20k points, use brute-force"), after a selective filter (section 9), and as ground truth. "Local" or "lite" modes of databases often are exact search (Qdrant's Python local mode, Milvus Lite), so their recall is 1.0 and their speed is not the server's: read back which index is actually used before benchmarking.

Sources for the thresholds, and what the Tool map found in lite modes (provenance)

FAISS: The Faiss library, Fig. 10; ScaNN: algorithms.md, both vendor docs. After a filter, 300 rows are cheaper to scan than any walk. The parent's Tool map found that Qdrant's Python client in local mode and Milvus Lite both scan every vector (Milvus Lite even after reporting an HNSW index); a Qdrant server below indexing_threshold has no graph either.

Time is bytes read: move N and watch the point slide along the line

3. IVF: k-means cells, nlist and nprobe

First way to read less: group similar vectors, and look only in the groups nearest the query. An inverted file index (IVF; from text search's inverted index, here a list of vectors per cell) runs k-means once to pick nlist centroids and files every vector in the list of its nearest centroid; each list is a cell (the Voronoi region nearer that centroid than any other). A query is compared with the nlist centroids, then only the nprobe nearest cells are scanned. On SciFact with nlist 72 (≈ √5,183, as the parent's Tool map used), nprobe 8 scans 11% of the cells.

distances per query ≈ nlist + nprobe · N / nlist
nlist
number of cells (FAISS: nlist; pgvector: lists; Milvus: nlist)
nprobe
cells scanned per query (pgvector: ivfflat.probes)

For a fixed share of cells probed this is smallest at nlist ≈ √N (The Faiss library, Eq. 18: "K + P × N/K" is minimised at K = √(P N), published). FAISS's default is nprobe = 1 (IndexIVF.h line 69), the reason an untuned IVF index disappoints.

The boundary problem, measured. A true neighbour can sit just across a cell wall (the orange ring in the hero). Where do SciFact's true top-10 neighbours live, counted by the rank of their cell among the query's nearest cells? measured here

Only half the true neighbours are in the nearest cell

300 test claims × 10 true neighbours = 3,000. Rank 1 = the cell whose centroid is nearest the claim. nlist 72.

Only 48% sit in the nearest cell, so nprobe 1 finds 0.482 of the true top 10; nprobe 8 reaches 0.901 and nprobe 32 0.992. In 1,024 dimensions "near the query" spreads over many cells. More cells make each smaller, so more probes are needed for the same recall, but each probe is cheaper:

Drift. The centroids describe the data they were trained on. Train them on SciFact only, then add the other three collections (25,039 vectors, nlist 158): the biggest list grows to 3,480 vectors against 399 after retraining, and nprobe 16 scans 6,477 distances against 2,837 for recall 0.886 against 0.914 measured here. Uneven lists make latency vary by query; retrain periodically (pgvector's IVFFlat too).

Training sample, seeds and FAISS's IVF code (depth)

k-means is trained on a sample. FAISS subsamples to 256 points per centroid and warns below 39 (faiss/Clustering.h lines 44 and 46: min_points_per_centroid = 39, max_points_per_centroid = 256; the warning at Clustering.cpp lines 113 to 120). On SciFact with nlist 72, training on 5% of the corpus (259 points, 3.6 per centroid) instead of all of it changed recall at nprobe 8 from 0.913 to 0.889, but made the lists much more uneven (coefficient of variation of list sizes 0.85 against 0.44). Two k-means runs on the same vectors fed in a different order gave nprobe-1 recall of 0.482 and 0.498: report IVF numbers with the seed measured here.

faiss/IndexIVF.cpp at v1.15.1, lines 351 to 365 (inside IndexIVF::search; arguments abridged)
quantizer->search( // step 1: the nprobe nearest centroids sub_n, sub_x, cur_nprobe, coarse_dis.get(), idx.get(), ...); invlists->prefetch_lists(idx.get(), ...); search_preassigned(sub_n, sub_x, k, idx.get(), ...); // step 2: scan those lists
faiss/IndexIVF.h at v1.15.1, line 69
size_t nprobe = 1; ///< number of probes at query time
IVF in one line
Solves exact search's linear cost with a cheap build and little extra memory (the centroids: nlist × d floats). Costs the boundary problem, a training step, and drift. Tune nprobe on your own queries; start with nlist ≈ √N (FAISS's decision tree goes further at scale: 16k cells below 1M vectors, 64k below 10M, 1M cells below 1B, with an HNSW index over the centroids) and expect to probe 5 to 15% of the cells for recall near 0.9 on embedding data like this.

More probes buy recall; more cells need more probes, each one cheaper

4. Quantization: storing each vector in fewer bytes

IVF reduces how many vectors a query touches; quantization reduces how many bytes each one takes, so more fit in memory and each comparison reads less. A 1,024-dimension float32 vector is 4,096 bytes; at 100 million vectors that is 410 GB before any index. Six ways to store fewer bytes, from gentle to aggressive:

FamilyWhat is stored per vectorbytes (d = 1,024)How distance is computed
float16each number in 16 bits2,048as float32, after conversion
Scalar int8 (SQ8)each number mapped to 0..255 within its learned range1,024on decoded values
Scalar int4 (SQ4)each number in 4 bits512on decoded values
Binarythe sign of each number, 1 bit128Hamming distance (count differing bits)
RaBitQ1 bit per dimension after a random rotation, plus a few floats136an unbiased estimator with an error bound
Product quantization (PQ), m sub-vectorsm one-byte ids of learned sub-vector centroidsm (8 to 256)m table look-ups and additions

Product quantization (Jégou, Douze and Schmid, TPAMI 2011), concretely: cut each 1,024-number vector into m = 16 sub-vectors of 64 numbers; for each of the 16 positions learn, with k-means, a codebook of 256 centroids (8 bits); store the vector as 16 bytes, the id of the nearest centroid at each position. The codebooks (256 × d floats in total, 1 MB for d = 1,024) are shared by the whole collection. At query time the query is not quantized: each of its 16 sub-vectors is compared with that position's 256 centroids once, giving a 16 × 256 distance table, and any stored vector's approximate score is the sum of the 16 entries its code picks. Per candidate the work drops from d multiply-adds over 4d bytes to m additions over m bytes. Fig. 2 in section 5 shows the table and one candidate's 16 bytes on a real index.

score(q, x) ≈ ∑j=1..m Tj[ codej(x) ],   Tj[c] = qj · centroidj,c
m
sub-vectors per vector, one byte each
Tj
row j of the m × 256 table, built once per query

Leaving the query unquantized is asymmetric distance computation (ADC), which the paper shows beats quantizing the query too.

ADC against SDC, and FAISS's distance table (code and depth)

"For m=8 we obtain the same accuracy for ADC and k*=64 as for SDC and k*=256" (Section V, published, authors' runs).

faiss/impl/ProductQuantizer.cpp at v1.15.1, lines 443 to 456 (L2 version; compute_inner_prod_table at line 472 is the same with dot products)
void ProductQuantizer::compute_distance_table(const float* x, float* dis_table) const { ... for (size_t m = 0; m < M; m++) { fvec_L2sqr_ny<SL>( dis_table + m * ksub, // row m of the table: ksub = 256 entries x + m * dsub, // the query's m-th sub-vector get_centroids(m, 0), // the 256 centroids of position m dsub, ksub); }

What each byte budget keeps, SciFact with Qwen3-Embedding and the four corpora stacked measured here; "rescore" means: take the best 10 × r by approximate score, re-rank them with the float32 vectors, keep 10.

  • int8: recall 0.995 at a quarter of the bytes; int4 0.946.
  • PQ alone is lossy, PQ with rescoring is not. 16-byte codes alone find 0.450 of the true top 10; rescoring the best 100 finds 0.914, the best 400, 0.988. The reconstruction error falls from 0.452 (m = 8) to 0.055 (m = 256), in squared distance on unit vectors.
  • OPQ helps PQ at equal bytes by learning a rotation first: m = 16 from 0.450 to 0.579 (details below).
  • Binary needs rescoring; RaBitQ needs less. Sign bits alone: 0.674; with 100 candidates rescored: 0.990. RaBitQ (Gao and Long, SIGMOD 2024) stores about the same 136 bytes but estimates distances better: 0.814 alone, 1.000 with 100 rescored. Its paper proves an error bound of O(1/√d) and reports beating PQ "by a clear margin" (published, authors' runs).
Rescoring is not free
It needs the full vectors somewhere: in RAM (then compression saved scan bandwidth, not memory), on SSD, read for the shortlist only (DiskANN's design, section 7), or in object storage. Count it in the memory budget (section 11).

Which model tolerates quantization, and Matryoshka truncation, belong to Embedding models.

OPQ, and what larger models keep under quantization (depth)

Optimized product quantization (Ge et al., CVPR 2013) first learns a rotation so each sub-vector carries a balanced share of the information: m = 64 from 0.688 to 0.797 here, for one d × d multiply per query.

Published on larger models: Hugging Face kept about 96% of retrieval quality with binary codes plus rescoring (32 times less memory) and about 99% with int8 (blog, 2024-03-22) published; the share kept depends strongly on the model, as the 384-dimension Quora run on Search and vector databases shows (pgvector's halfvec and binary_quantize).

int8 is almost free; PQ and binary need rescoring, and with it recover

5. IVF-PQ, residuals and rescoring

The classic billion-scale recipe combines both ideas: IVF picks the cells, PQ compresses what is inside them (Jégou et al. call it IVFADC). One refinement: PQ encodes the residual, the vector minus its cell's centroid, which is smaller and so quantizes with less error; for inner product the score is then the query·centroid term plus the table sum.

Fig. 2 is a real FAISS 1.15.1 index over the 5,183 SciFact abstracts: 72 cells, each abstract also stored as a 16-byte PQ code (16 sub-vectors of 64 dimensions). Step one real claim through it, then switch the method to run the same claim and cells through IVF-Flat or with rescoring. Predict first: with 16-byte codes and no rescoring, how many of the exact top 10 will survive?

  1. Coarse step. The claim (orange) is compared with the 72 k-means centroids: one post per cell, nearest first from the front left, height its similarity to the claim (72 × 1,024 multiply-adds). Each abstract lives in exactly one cell, the one whose centroid is nearest to it.
  2. Probe the nearest cells. Only the nprobe nearest cells are opened (lit); their lists rise, labelled with how many abstracts each holds. Every abstract in them is a candidate. A true neighbour in a cell left shut cannot be found by any later step: the boundary problem.
  3. Build the lookup table once per query. IVF-PQ splits the claim into 16 pieces of 64 numbers and compares each with the 256 centroids of its codebook: a 16 × 256 table (262,144 multiply-adds, 16 KB), the glass plate. IVF-Flat has no table; it scores every candidate exactly from its float32 vector, 1,024 multiply-adds over 4,096 stored bytes each.
  4. Score one candidate from its 16 bytes. The candidate is stored as 16 byte values, each the id of the centroid nearest to one of its pieces. Each byte picks one entry in its row of the table (the bars: blue where the centroid points the same way as the claim's piece, orange the opposite way). Its score is the claim·centroid term plus those 16 entries: 16 additions, no multiplication. Beside it, the exact similarity.
  5. Rank. The 20 best candidates by the method's score, best on the left; green when the abstract is in the exact top 10. With IVF-PQ a dark tick marks each one's exact score: the gap is the quantization error, and it reorders neighbours. With rescoring, the 100 best by PQ score are re-scored with their float32 vectors (100 × 1,024 multiply-adds) and re-sorted.
  6. Result. The 10 returned, against the exact top 10 (the table below). Switch the method or nprobe to run the same claim through the others: rescoring recovers what PQ reordered, never a neighbour in a cell that was not probed.

All four claims, every setting, and how the page recomputes FAISS's scores (table)

Measured on Apple M1 Pro (CPU), deterministic. The page scores candidates with the same arithmetic as FAISS's IndexIVFPQ for inner product with residuals (score = query · centroid + the sum of 16 table entries); the generating script checks this against FAISS's own scores (largest difference ) and stores tables and exact similarities rounded to 1/30,000.

Over all 300 claims, IVF72 with 32-byte PQ codes: recall alone stops rising at about 0.57 however many cells are probed (the PQ error, not the cell boundary, is the limit); rescoring the best 100 lifts it to 0.916 at nprobe 32 measured here. The parent's Tool map found the same in LanceDB, whose default index is IVF-PQ: 0.59 at defaults, 0.97 with refine_factor 10 (rescoring) on SciFact with bge-small.

FAISS source: the residual score decomposition (code)
faiss/IndexIVFPQ.cpp at v1.15.1, lines 379 to 390 (comment above the precomputed tables); by_residual = true by default (line 64)
* During IVFPQ search with by_residual, we compute * * d = || x - y_C - y_R ||^2 * * where x is the query vector, y_C the coarse centroid, y_R the * refined PQ centroid. The expression can be decomposed as: * * d = || x - y_C ||^2 + || y_R ||^2 + 2 * (y_C|y_R) - 2 * (x|y_R) * --------------- --------------------------- ------- * term 1 term 2 term 3

For inner product the score splits into the coarse term and the table term; for L2 FAISS adds the third term it can precompute.

The general shape: candidates cheap, final ranking exact
Every compressed index ends the same way: a cheap approximate stage generates candidates and an exact stage re-ranks a short list. ScaNN calls it "reorder", LanceDB "refine_factor", FAISS "IndexRefine", Qdrant "rescore"; DiskANN reads the full vector from SSD during the walk. It is the cross-encoder-after-retriever pattern one level down (Rerankers and late interaction).

6. HNSW: a graph you walk

Second way to read less: link each vector to a few neighbours, and find the query's neighbours by walking. In a proximity graph every stored vector is a node with links to some nearby nodes. A greedy search starts at some node, moves to whichever neighbour is closest to the query, and repeats until no neighbour is closer. With the right mix of short links (precision) and long links (crossing the collection fast), the walk reaches the query's region in few steps. HNSW (hierarchical navigable small world; Malkov and Yashunin, arXiv 1603.09320, IEEE TPAMI) adds two things to such a graph: layers and a neighbour-selection heuristic. Watch both on a real graph before the details.

Fig. 3 is a real graph: 240 real passages (60 from each collection, Qwen3-Embedding; colours SciFact, NFCorpus, HotpotQA, QASPER) inserted by a line-by-line port of hnswlib 0.8.0, M = 5, efConstruction = 40, so it can be drawn. Exact search would compute 240 distances. Predict before switching to "Closest-M links": will the four colours stay connected to each other? Positions are a t-SNE map for drawing only; distances are computed in 1,024 dimensions.

  1. Layers. Every passage is a node on layer 0 (the floor); a node also sits on every layer up to its random level, so each layer holds about 1 in M of the one below: 60 nodes on layer 1 and 11 on layer 2 here (dotted lines tie a node to its copy on the floor).
  2. How a node chose its links. One insert, close up. It searched with efConstruction, then took the candidates nearest first: green links were kept; a red dashed candidate was rejected because a neighbour already kept (thin red line) is closer to it than the new node is, so the link budget goes to other directions. In the Closest-M graph nothing is rejected: the M closest are kept, whatever their direction.
  3. Enter at the top. The query (orange pin through the layers) starts at the single entry point on the highest layer and walks greedily: compare the query with the current node's neighbours (the flows), move to the closest, repeat until none is closer.
  4. Drop a layer. The node reached becomes the start one layer down, where there are more nodes and shorter links, and the same greedy walk continues.
  5. Layer 0: best-first search, ef = 8. On the floor the search keeps the 8 best nodes seen: expand the closest unexpanded candidate, compute the distance to each unvisited neighbour; solid ones joined the candidates, grey dashed ones were dropped.
  6. Stop. The search ends when the closest open candidate is worse than the worst of the 8 kept (hnswlib searchBaseLayerST, line 348). The lit nodes are every distance it computed.
  7. Result. The 4 best of the 8 kept (green rings) against the exact top 4 (orange rings where missed), for the distances in the readout against 240 for exact search.

The same question on all three graphs (table)

What to look for. Layers: most nodes stay on layer 0; about one in M reaches layer 1. Closest-M: the M closest are kept whatever their direction, so links bunch up inside a dense corner and a cluster can end up reachable only through one or two nodes. At 240 points the layers save little: the figure shows the mechanism, the charts below what each half buys at 5,183 and 25,039 vectors.

Layers. Every node is on layer 0 and on layers up to its level, drawn as floor(−ln U · mL) with U uniform in (0, 1) and mL = 1/ln M: a node reaches level l with probability M−l, so each layer is about M times smaller ("the skip list parameter p=1/M", Section 4.1).

Search. From the single entry point (the highest node), walk greedily on each upper layer, then on layer 0 run a best-first search keeping the ef best seen: expand the closest unexpanded candidate, keep neighbours that beat the worst of the ef, stop when the closest open candidate is worse than the worst kept. ef is the runtime dial: recall up, latency up, no rebuild. FAISS's stop rule differs (impl/HNSW.cpp lines 1164 and 1224), so "ef 64" is not the same recall in two libraries.

Build. An insert runs the same search with a wider list, efConstruction, on every layer from its level down, then the heuristic (Algorithm 4) takes candidates nearest first and keeps one only if it is closer to the new node than to every neighbour already kept. A rejected candidate is reachable through the neighbour that blocked it, so the link budget goes to other directions: in clustered data, a link to the next cluster (the paper's Fig. 2; red dashed in Fig. 3).

hnswlib read line by line: levels, the stop rule, the heuristic, reverse links, and the Python port that checks the reading (code and depth)

hnswlib computes the level exactly as the paper says (mult_ = 1 / log(1.0 * M_), hnswalg.h line 142). Its layer-0 search keeps ef results (efSearch in FAISS, hnsw.ef_search in pgvector); FAISS stops after more than efSearch expansions, or when efSearch closer candidates are already queued.

hnswlib/hnswalg.h at v0.8.0, line 142 and lines 207 to 211
mult_ = 1 / log(1.0 * M_); ... int getRandomLevel(double reverse_size) { std::uniform_real_distribution<double> distribution(0.0, 1.0); double r = -log(distribution(level_generator_)) * reverse_size; return (int) r; }

FAISS computes the same distribution as a table (impl/HNSW.cpp lines 80 to 93, exp(-level / levelMult) * (1 - exp(-1 / levelMult)) with levelMult = 1/ln M, line 63). Measured on SciFact measured here:

hnswlib/hnswalg.h at v0.8.0, searchBaseLayerST, lines 342 to 348 and 395 (comments added)
while (!candidate_set.empty()) { std::pair<dist_t, tableint> current_node_pair = candidate_set.top(); // closest open candidate dist_t candidate_dist = -current_node_pair.first; bool flag_stop_search; if (bare_bone_search) { flag_stop_search = candidate_dist > lowerBound; // lowerBound = worst of the ef kept ... // then, for each unvisited neighbour of that candidate: flag_consider_candidate = top_candidates.size() < ef || lowerBound > dist;
hnswlib/hnswalg.h at v0.8.0, getNeighborsByHeuristic2, lines 457 to 478 (abridged)
while (queue_closest.size()) { if (return_list.size() >= M) break; std::pair<dist_t, tableint> curent_pair = queue_closest.top(); dist_t dist_to_query = -curent_pair.first; // candidate to new node queue_closest.pop(); bool good = true; for (std::pair<dist_t, tableint> second_pair : return_list) { dist_t curdist = fstdistfunc_(getDataByInternalId(second_pair.second), getDataByInternalId(curent_pair.second), ...); // candidate to a kept neighbour if (curdist < dist_to_query) { good = false; break; } } if (good) return_list.push_back(curent_pair); }

Three details that the paper's prose does not make obvious and the code does:

  • The new node keeps at most M links, even on layer 0 (line 513: getNeighborsByHeuristic2(top_candidates, M_)); layer 0 lists can hold 2M (line 113: maxM0_ = M_ * 2, the paper's recommendation "2*M is a good choice for Mmax0") and fill up through reverse links from later nodes.
  • Reverse links are pruned again: when a neighbour's list is already full, adding the new node re-runs the heuristic over the old list plus the new node, and something is dropped (lines 586 to 610). Links are not symmetric.
  • The next layer down starts from the closest node found (line 524).

To check this reading, the page ships a line-by-line Python port of hnswlib's insert and search (src/scripts/pyhnsw.py) and compares it with hnswlib on all 5,183 SciFact vectors, M 16, efConstruction 200, with hnswlib's own levels: 5,530 of 5,539 neighbour lists come out identical in content and order (the rest differ by floating-point ties), and all 300 test claims get the same top 10 at ef 10, 40 and 100 measured here: . The port draws Fig. 3 and counts distance computations where hnswlib's Python API does not.

The knobs, measured. FAISS IndexHNSWFlat on SciFact, built on one thread; recall@10 against exact search and distance computations per query measured here:

  • M sets quality and size; too small and the graph falls apart: at M = 4 (efConstruction 16), 134 of 5,183 nodes are unreachable on layer 0, so no query can return them; M = 8, 3; from M = 16, none (the paper: typical M 6 to 48).
  • efConstruction stops buying quickly: at M = 16, ef 40, recall 0.981 (efC 40), 0.990 (100), 0.991 (200); the paper asks for construction-time recall "close to unity ... (0.95 is enough for the most usecases)".
  • ef is the cheap dial: ef 10 gives 0.913 with 254 distances, ef 100 0.999 with 1,165 (exact: 5,183). Defaults differ widely (hnswlib ef 10, FAISS efSearch 16, pgvector ef_search 40; dated table in section 13).
Library defaults reproduced, and Quora at pgvector's settings (depth)

The parent's Tool map measured what library defaults give on SciFact with bge-small: hnswlib at its default ef 10 found 0.876 of the true top 10 (0.998 at ef 100), FAISS at efSearch 16 0.964, Qdrant's server 0.996, pgvector 0.985. This page reproduces the hnswlib and FAISS numbers exactly (0.876, 0.964, 0.998) and adds hnswlib at pgvector's settings (M 16, efC 64, ef 40): 0.977 measured here, a little under pgvector's 0.985 because two implementations draw different levels and stop differently. On the same 522,931 Quora vectors and 1,000 queries the Search and vector databases page used, hnswlib at M 16, efConstruction 200, ef 40 found 0.995 of the true top 10 against pgvector's 0.989 at m 16, ef_construction 64, ef_search 40 measured here; the larger efConstruction is the likely reason (not isolated here).

M fixes the graph; ef is the cheap dial along each curve

What each half of HNSW buys. Remove one idea at a time, with the port, on the same vectors, order and levels measured here:

On the four corpora stacked (clustered by source, the case the heuristic was designed for), "keep the M closest" costs 4 points at ef 40 (0.906 against 0.949); a single layer with the heuristic matches full HNSW (0.953). On SciFact alone, one topic, neither change mattered much. Munyampirwa, Lakshman and Coleman found the same at up to 100M vectors in 96 to 960 dimensions: the hierarchy helps only below about 32 dimensions, because a few well-connected "hubs" do its job (arXiv 2412.01940, published, authors' runs). It costs little memory (about 1/(M−1) extra lists), so libraries keep it.

"Down with the Hierarchy" in its own words (provenance)

"Down with the Hierarchy: The 'H' in HNSW Stands for 'Hubs'", v3, ICML 2025 workshop: a flat graph had "latency and recall performance essentially identical to the original algorithm but with less memory overhead"; hubs are nodes that every search passes through early.

HNSW in one line
Solves high recall at low latency with no training step; inserts work any time. Costs memory (the full vectors plus 2M links per node, in RAM), slow builds (each insert is a search), and deletes that leave tombstones (section 10). Tune M once (16 to 32), efConstruction once (100 to 200), and ef per query on your own data.

The pruning heuristic matters on clustered data; the layers do not

7. DiskANN and Vamana: the graph on SSD

HNSW wants the full vectors and the links in RAM: hundreds of gigabytes at a billion 128-dimension vectors. DiskANN (Subramanya et al., NeurIPS 2019) keeps only small PQ codes in RAM to steer the walk, and stores on SSD, per node, "its full precision vector x_i followed by the identities of its ≤ R neighbors" (Section 3.2). Each hop is one random SSD read, and the full vector that arrives re-scores the candidate for free. Its headline: a billion SIFT vectors on one workstation with 64 GB of RAM, "> 5000 queries a second with < 3ms mean latency and 95%+ 1-recall@1" on 16 cores (published, authors' runs, 2019).

One hop is one SSD read, if a node fits in a sector

The graph is Vamana: one layer, built in two passes from a random start graph, with one new knob α in its pruning rule RobustPrune: keep the closest remaining candidate p*, drop every p′ with α · d(p*, p′) ≤ d(p, p′), repeat (Algorithm 2). At α = 1 this is HNSW's heuristic; α > 1 prunes less, keeping edges that cut the distance to the query by a factor α per hop: fewer hops, which matters when each hop is an SSD read. Search keeps L candidates and expands until all are expanded (Algorithm 1), fetching the W best at once on SSD (beam width 2 to 8).

The paper's words on α (provenance)

"both HNSW and NSG have no tunable parameter alpha and implicitly use alpha = 1" (Section 2.4); with α > 1 "the distance to the query decrease[s] by a multiplicative factor of α" at each hop.

Not run here: the official DiskANN (its Python wheels are Linux x86_64 and Windows only; the current code is Rust). This page implements Vamana from the paper's three algorithms in Python (src/scripts/vamana.py, about 120 lines; not the authors' code) and measures it against HNSW on the same SciFact vectors measured here:

  • Hops track L. Vamana expands about L nodes per query: at L = 40, 44 hops for recall 0.989; HNSW at ef 40 walks 45 for 0.992. The paper's "2 - 3 times fewer hops ... compared to HNSW and NSG" is for large datasets (Section 4.2) and is not tested here.
  • α in 1,024 dimensions behaves differently from the paper's 128. α = 1 keeps on average 16.0 of the allowed 32 edges, α = 1.2 all 32, and the extra edges are short ones. The α = 1 graph had half the edges for the same recall: half the memory for links on data like this.
  • Dimension matters on disk in a way it does not in RAM (the diagram above): a node is d × 4 + R × 4 bytes, 768 for SIFT with R = 64 (several per 4 KB sector; the paper's Section 3.5 notes a degree-128 neighbourhood plus a 128-d vector fits one sector), but 4,224 for Qwen3-Embedding with R = 32, just over one 4,096-byte sector: two reads per hop unless the vector is stored in float16 or the degree lowered.
Why α adds short edges: distance concentration, measured (depth)

With α = 1.2 the median rank of an edge's target among the node's neighbours falls from 24 to 20, and the share of edges to nodes outside the 50 nearest from 29% to 1%. The reason is distance concentration: in high dimensions a point's 10th neighbour (median distance 0.92) is nearly as far as its typical graph neighbour (0.96), so the α margin rarely triggers a prune.

Deletes on a disk graph (FreshDiskANN) are in section 10; products built on Vamana (Milvus DISKANN, pg_diskann, pgvectorscale, SQL Server 2025, Redis SVS-VAMANA) in the dated table in section 13.

At 5,183 vectors Vamana and HNSW are equally good, hop for hop

8. ScaNN: quantize for ranking, not for reconstruction

PQ's codebooks reconstruct each vector as faithfully as possible, but for inner-product search the error along the vector's own direction matters more: it moves its score for every similar query. Anisotropic vector quantization (Guo et al., ICML 2020), the core of Google's ScaNN, weights that parallel residual by a factor η more (η = 4.125 at threshold T = 0.2) and reports better recall than reconstruction loss at the same bit rate on Glove-1.2M (published, authors' runs). Measured here on SciFact measured here, it did not beat plain reconstruction at equal code size (0.867 against 0.885 at 256 bytes, 0.654 against 0.668 at 64), and with reordering both reached the same recall: measure a published trick on your own vectors before paying for it.

ScaNN's rules of thumb, every configuration, and why it ran in Python 3.9 (table and depth)

The paper also reports the fastest high-recall results on ann-benchmarks.com at the time; its dataset (Glove-1.2M, 100 dimensions) and recall regime differ from these unit-length 1,024-d vectors, so the two results do not contradict each other. ScaNN's own rules of thumb: brute force below 20,000 points; "score with AH, then rescore" below 100,000; "partition, score with AH, then rescore" above, with about √N leaves and dimensions_per_block 2 (algorithms.md, vendor docs). Run here in a Linux container (ScaNN 1.4.2 publishes Linux wheels only; recall only, no timing). The partitioned configuration behaved like IVF with rescoring: 0.937 when searching 16 of 72 leaves.

AH = asymmetric hashing, ScaNN's PQ-like scoring with 16 centres per block (4 bits); dims_per_block 2 gives d/4 bytes per vector. "Tree" partitions into √N leaves like IVF. Reorder 100 = rescore the best 100 exactly. ScaNN 1.4.2's aarch64 wheels tagged for Python 3.12 and 3.13 refuse to import ("module was compiled for Python 3.9"), so it ran in a python:3.9-slim Linux container on this Mac.

9. Filtered search: where indexes break

Real queries come with conditions: "chunks of this paper", "documents this user may read", "published this year". A filtered vector search must return the k nearest vectors among those that pass. Two properties of the filter decide which strategy works: selectivity, the share of rows that pass ("own paper" in QASPER keeps 0.35% of the 6,463 chunks, about 23), and correlation with the query, whether the rows that pass are near the query anyway (a question's own paper is correlated; a random other paper of the same size is not; a filter on a different collection than the query came from is anti-correlated).

StrategyHowFails when
Pre-filterfind the passing rows with an ordinary index (B-tree, bitmap), then exact search over themthe filter keeps many rows (then it is a big exact scan)
Post-filterANN search for k′ > k results, drop those that failthe filter is selective or anti-correlated: few of the k′ pass
In-graph filterwalk the graph as usual, but only passing nodes enter the resultsselective filters: the walk must visit most of the graph to collect k passing nodes
Predicate-aware graphwalk only (or mostly) through passing nodes, with extra links so they stay connected: ACORN, Qdrant's payload links, Filtered-DiskANNbuild cost and memory for the extra links

Why selective filters break graph walks, on Fig. 3's real graph: a walk that may only step on passing nodes finds them scattered into pieces with no links between them.

  1. The graph. Layer 0 of Fig. 3's HNSW graph: 240 passages and every link between them.
  2. A filter keeps a few. Passing nodes stay lit; failing ones fade, and with them every link that touches one. A random attribute is uncorrelated with the links, so the survivors fall apart into many small pieces: a walk that may only step on passing nodes cannot get from one to another. A filter on one collection is correlated with the links (similar passages are linked) and stays almost in one piece.
  3. In-graph filter: walk through the failures. hnswlib keeps every link and lets the walk pass through failing nodes, never returning them (the orange path joins two pieces through white failing nodes). Always connected, but most of the distances go to nodes it may not return.
  4. Two-hop links. ACORN's repair: from a passing node, also step to passing nodes two links away (green dashed). The pieces join up without visiting failing nodes; ACORN-1 builds the graph without neighbour pruning so that more such links exist.

hnswlib's in-graph filter is the same code path as deleted nodes: a node that fails is still expanded (its neighbours are explored) but never added to the results, and the stop rule waits for ef passing results. FAISS's HNSW with an IDSelector filters the same way but keeps its own stop rule (at most efSearch expansions), so it gives up earlier and returns fewer, sometimes wrong, results.

hnswlib source: the filter inside the search loop (code)
hnswlib/hnswalg.h at v0.8.0, searchBaseLayerST, lines 353 and 406 to 408
flag_stop_search = candidate_dist > lowerBound && top_candidates.size() == ef; ... if (bare_bone_search || (!isMarkedDeleted(candidate_id) && ((!isIdAllowed) || (*isIdAllowed)(getExternalLabel(candidate_id))))) { top_candidates.emplace(dist, candidate_id);
Predict: a filter keeps 1% of the 25,039 stacked vectors, at random. Which is cheaper at recall 0.95?

Measured on the topic's data measured here; ef = 100, k′ = 100 unless stated; "distances" is the work per query:

  • Post-filtering a selective filter fails, and anti-correlation makes it worse. With "own paper", 100 unfiltered neighbours contain on average 4.3 chunks of the right paper, so recall is 0.43; with an uncorrelated paper of the same size, 0.03, and 756 of 892 questions got nothing back at all.
  • hnswlib's in-graph filter is always right and sometimes absurdly expensive. For "own paper" it found every true neighbour but computed 6,513 distances, the whole collection and more, where pre-filtering computes 23.
  • Pre-filtering wins below a crossover. On the 25,039 stacked vectors with a random attribute, pre-filter work equals the rows kept (251 at 1%, 2,588 at 10%, 141 at 0.5%); the in-graph filter needs 22,021 distances at 1% and 6,156 at 10%, and is cheaper only from about 10 to 25% selectivity. Every production planner encodes this crossover.
  • ACORN-1 fixes the middle. Written here from Patel et al. (SIGMOD 2024, section 5.3): build HNSW without neighbour pruning, then walk through one-hop and two-hop neighbours that pass. At 1% recall 0.918 for 143 distances; at 10%, 0.953 for 621. Weak spot: very selective filters (0.093 at 0.1%).
  • Qdrant got all of them right (v1.19.2 server, payload index on the paper id): forced onto its filtered graph, recall 0.998 at hnsw_ef 16; at the default threshold its planner chose payload index plus exact scoring, recall 1.0. It adds graph links per indexed payload value and picks the path from a cardinality estimate.

Pre-filtering wins below a crossover; graph walks win above it

Work per query (distances, log scale) against selectivity, random attribute on the four corpora, each strategy at its cheapest setting that reaches recall 0.95, drawn only where some setting does. Crossover near 10 to 25% here.

Every strategy and setting, under filters of every kind

The chart on the right: recall@10 against the exact filtered top 10, against distances per query (deterministic; one hnswlib graph per collection, M 16, efConstruction 200). For the random attribute, step the selectivity from 0.1% of rows kept to all of them and watch the strategies trade places; the other filters are one picture each.

    ACORN-1's other weak spots, and Qdrant v1.19.2 on the same filters (depth)

    In this implementation ACORN-1 also loses recall with no filter at all (0.873 at ef 100: truncating the two-hop list to M drops good neighbours), which the paper handles with the denser ACORN-γ build; a two-hop search on the ordinary pruned graph did worse (0.866 at 1%, 0.486 on QASPER's own-paper filter, where ACORN-1 reached 0.566). The paper reports "2-1000x higher queries per second ... at 0.9 recall compared to prior methods" (published, authors' runs).

    Qdrant ran in Docker with the payload index created before the graph. With full_scan_threshold at its 10 KB minimum, the 892 "own paper" searches all went down the filtered-graph path ("filtered_large_cardinality"); with the default threshold (10,000 KB) every search took payload index then exact scoring ("filtered_small_cardinality"). Vendor docs and source, read 2026-10-14.

    Qdrant does not expose distance counts, so it is not on the chart.

    What production systems do
    pgvector 0.8 keeps walking until enough rows pass (iterative index scans, measured on Search and vector databases, section 10); Qdrant plans per segment and uses payload links; Weaviate and Qdrant ship ACORN (versions in section 13). Multi-tenancy is this problem with a very selective, perfectly correlated filter: pre-filter small tenants, partition large ones (the filter becomes routing); RAG in production covers it as access control.
    The NeurIPS'23 filtered track (published)

    The NeurIPS'23 Big-ANN filtered track (YFCC 10M CLIP vectors, queries with one or two tags) was won by ParlayANN at 37,902 queries per second at recall@10 ≥ 0.9, more than 11 times the FAISS baseline, using per-tag indexes for common tags and plain lists for rare ones (arXiv 2409.17424, independent benchmark).

    10. Updates and deletes

    Flat: append or remove rows. IVF: inserts go into the nearest existing cell, deletes remove list entries; retrain against drift (section 3). HNSW: an insert is a search plus link updates, the same work per vector as building. A delete cannot simply remove a node, because other nodes route through it: hnswlib, like pgvector and FreshDiskANN, marks it as deleted, a tombstone (a flag bit in the node's link-list header, *ll_cur |= DELETE_MARK, hnswalg.h line 877). Searches still walk through it but never return it, exactly the in-graph filter of section 9.

    With half the rows deleted, a query at ef 40 computes 977 distances against 544 in a rebuilt graph, and the dead vectors still occupy memory. Reusing deleted slots for new vectors (hnswlib's allow_replace_deleted) costs a little recall, because the old links stay around a vector that may belong elsewhere (details below). FreshDiskANN's answer is batch consolidation: after "1-10% of the index size" is deleted, reconnect the neighbours of each deleted node to its out-neighbours and re-prune (arXiv 2105.09613, published, authors' runs); pgvector does the equivalent in VACUUM (Search and vector databases page). In every system the honest long-term fix is the same: rebuild periodically, or per segment, as Lucene does when it merges segments.

    Replacing deleted slots, measured (depth)

    Replacing 30% of SciFact with NFCorpus abstracts through allow_replace_deleted gave recall 0.848 at ef 10 against 0.900 for a graph built fresh on the same final vectors (0.982 and 0.991 at ef 40) measured here.

    Changing the embedding model is not an update
    Vectors from two models are not comparable: a new model means re-embedding everything and building a new index, usually side by side with the old one until the switch. The Search and vector databases page gives the column-by-column recipe; RAG in production the dual-index operations.

    Tombstones keep recall but cost work: half the rows dead, nearly twice the distances

    hnswlib tombstones on SciFact (M 16, efC 200), recall against the exact top 10 of the rows still alive, against a graph rebuilt on the live rows only measured here.

    11. Memory and build time, from formulas checked against measurement

    Memory is usually the binding cost: graph indexes are fastest when everything is in RAM. Each index's size can be written down and checked against the bytes the library actually writes:

    IndexBytes, approximatelyWhere the terms come from
    FlatN · d · bthe vectors
    IVF-FlatN · (4d + 8) + nlist · 4dvectors and 8-byte ids in the lists; centroids
    IVF-PQN · (m + 8) + nlist · 4d + 256 · 4dcodes and ids; centroids; PQ codebooks
    hnswlib HNSWN · (4 + 8M + 4d + 8) + N/(M−1) · (4M + 4)per element: link count, 2M links of 4 bytes, the vector, an 8-byte label (hnswalg.h lines 120 to 121); upper layers on about 1/(M−1) of nodes
    FAISS IndexHNSWFlatN · 4d + N · 4 · (2M + M/(M−1)) + N · 12vectors (separate storage); neighbour slots per level; level and offset arrays

    Build time, single thread measured here, timed: FAISS HNSW (M 16, efConstruction 100) took 174 s for 522,931 Quora vectors, IVF-Flat 20.4 s. A graph build is N × (one search with efConstruction), which is why every database parallelises it and why bulk-loading before indexing beats inserting into a live graph.

    Every build time measured, and the paper's (table)

    FAISS HNSW M 16, efConstruction 100: 0.89 s for 5,183 vectors (1,024-d), 7.5 s for 25,039; hnswlib at its defaults (efC 200): 9.9 s and 65 s. IVF-Flat trains and fills in 0.36 s for 25,039; IVF-PQ adds codebook training (17 s). The HNSW paper reports a 10M SIFT build in about 3 minutes at efConstruction 100 on 40 cores (published, authors' runs).

    The vectors dominate; links and codes are small beside them

    Bars: the formulas above. Check table: the formula against the serialized size measured here. At M = 16 the graph is 8M + 12 bytes per vector on layer 0 plus about (4M + 4)/(M − 1) for the upper layers, about 145 bytes.

    12. Scaling to 100 million vectors and beyond

    How work per query grows with N, on prefixes of Quora (10,000 to 522,931 vectors) at a fixed recall target measured here:

    From 10,000 to 522,931 vectors (52 times more), exact search grows 52 times; IVF at recall 0.95 from 2,580 to 13,188 distances, roughly like √N; HNSW barely moves (437 to 297). On these vectors the graph's work is close to flat in N; the paper's claim is O(log N). The higher the recall target, the faster the work grows (IVF at 0.99: 4,957 to 73,111), as the Faiss library paper found on BigANN-1B, where IVF search time grew as N0.29 at recall 0.5 and N0.45 at 0.99 (published). Past one machine's memory, four techniques combine:

    • Compress in RAM (PQ, int8, binary, RaBitQ) and rescore from somewhere cheaper: with 64 GB for a billion vectors, NeurIPS'21 Big-ANN's in-memory track reached recall@10 of roughly 0.63 to 0.76 at 10,000 queries per second.
    • Put the graph on SSD (DiskANN) or the lists on SSD (SPANN): the SSD track's DiskANN baseline (8 vCPUs, 64 GB) reached roughly 0.90 to 0.95 at 1,500 queries per second.
    • Shard: search every shard for its top k and merge; merged recall is about the per-shard recall, latency the slowest shard's. Sharding by a key the queries filter on (a tenant, a date) lets most queries touch one shard. Replicate for queries per second and availability.
    • Use GPUs for builds and batched search (section 2).
    Sources, SPANN, and HNSW's memory at 100M (published)

    Big-ANN NeurIPS'21: arXiv 2205.03763, Tables 2 and 3 (independent benchmark). SPANN reports 90% recall@10 "in just around one millisecond with only 32GB memory cost" on billion-scale sets, about twice as fast as DiskANN at equal memory (NeurIPS 2021, published, authors' runs). Munyampirwa et al. measured hnswlib's peak build memory at 183 GB for 100M BigANN vectors (128-d), 113 GB for their flat graph (Table 6, published, authors' runs). ANN-Benchmarks, the standard independent comparison of libraries, tests at most about 10 million vectors on a single CPU (README, "as of April 2025"), so it says little directly about 100M to 1B behaviour.

    Exact grows with N, IVF like √N, HNSW barely at all

    13. Choosing an index

    Start from the hard constraint, almost always memory, then from how the data changes, then tune on your own queries. The Frontier tab puts every measured setting on one recall, speed and memory chart.

    SituationStart withWhy (evidence on this page)
    Under about 50,000 vectors, or queries in batchesFlat (exact), maybe float162.53 ms per query at 25,039 × 1,024 on one thread; recall 1.0; nothing to tune (section 2)
    Up to tens of millions, fits in RAM, changes oftenHNSW, M 16 to 32, efConstruction 100 to 200, ef tuned per query0.993 recall at 0.19 ms on 522,931 vectors (Frontier); inserts any time (section 6)
    RAM is tightHNSW or IVF over int8 (4× smaller), or IVF-PQ / RaBitQ with rescoringint8 keeps recall 0.995; 1-bit RaBitQ with rescoring 1.000 (section 4)
    Hundreds of millions to billionsIVF-PQ with a graph over the centroids, or DiskANN / SPANN on SSD, shardedBig-ANN 2021 and the DiskANN and SPANN papers (section 12)
    Selective filters (tenants, ACLs, one document)pre-filter + exact below a few percent; a filter-aware graph (ACORN, Qdrant payload links, pgvector iterative scans) abovecrossover near 10 to 25% here (section 9)
    Data mostly static, build time no objecta graph built with care (Vamana, NSG), or IVF with many cellssection 7; FAISS's decision tree

    Whatever you pick: measure recall against exact search on a few hundred real queries, then answer quality on labelled ones (section 1), and quote latency only with recall: FAISS IVF at its default nprobe 1 answers SciFact in 0.017 ms with recall 0.482 (Frontier).

    Corrected from the old "Embeddings and vector search" page
    • "HNSW is the default in pgvector, Qdrant, Weaviate and Milvus": pgvector has no default index (you create HNSW or IVFFlat yourself; the Search and vector databases page), and Qdrant only builds its graph once a segment passes indexing_threshold (parent's Tool map).
    • "Below about 1M vectors, nothing matters much": exact search over 522,931 vectors of 384 dimensions took 22 ms per query on one core here, and an untuned index loses recall at any size (FAISS IVF at nprobe 1: 0.482 on 5,183 vectors).
    • "The HNSW graph costs roughly M × 8 to M × 10 bytes per vector": from hnswlib's code it is 8M + 12 bytes per vector on layer 0 plus about (4M + 4)/(M − 1) for the upper layers, about 145 bytes at M = 16, checked against the file size in section 11. Consistent, now with its terms.
    • "ScaNN handled roughly twice the queries per second of the next-fastest of eleven libraries" (Google Research blog, July 2020): a vendor claim not re-checked here; this page's container run of ScaNN measured recall only (section 8).
    Library defaults, versions and products, dated (volatile: read 2026-10-14 unless stated)
    System (version)WhatValueSource
    hnswlib 0.8.0HNSW M / efConstruction / ef16 / 200 / 10Python binding defaults; hnswalg.h line 115 (ef_ = 10)
    FAISS 1.15.1 IndexHNSWFlatM / efConstruction / efSearch(you pass it; 32 is common) / 40 / 16impl/HNSW.h lines 141 and 144
    FAISS 1.15.1 IndexIVFnprobe1IndexIVF.h line 69
    FAISSRaBitQin FAISS by 1.11.0, 2025-04-24CHANGELOG
    pgvector 0.8.7m / ef_construction / ef_search16 / 64 / 40README (Search and vector databases page)
    Lucene (main)M / beam width / query16 / 100 ("beam width") / set per queryHnswGraphBuilder.java
    Elasticsearch 9.xm / ef_construction / query16 / 100 / num_candidatesdense_vector docs (vendor docs)
    Qdrant 1.19m / ef_construct / query16 / 100 / hnsw_efindexing docs (vendor docs)
    QdrantACORN-1 searchopt-in from v1.16.0 (2025-11-17)release notes
    Weaviate 1.40maxConnections / efConstruction / ef32 (64 on layer 0) / 128 / dynamic (100 to 500)vector index docs (vendor docs)
    WeaviateACORN filter strategyadded in v1.27, the default in v1.34filtering docs
    Milvus 3.0HNSW M / efConstruction / query30 / 360 / efHNSW docs (vendor docs)
    Milvus 3.0DISKANNMaxDegree 56, SearchListSize 100, PQCodeBudgetGBRatio 0.125, BeamWidthRatio 4DISKANN docs (vendor docs)
    DiskANNofficial codediskannpy 0.7.0 ships only Linux x86_64 and Windows wheels; the Rust code is DiskANN v0.60.0 (2026-10-05, per the parent's FACTS)PyPI, GitHub
    Products on VamanaDiskANN-style indexesAzure's pg_diskann and Cosmos DB, SQL Server 2025, Timescale's pgvectorscale (StreamingDiskANN), Redis 8.2's SVS-VAMANAdates and links on the Search and vector databases page and the parent's Tool map
    GoogleScaNN in productsAlloyDB's alloydb_scann; Vertex AI Vector Search is built on itSearch and vector databases page
    Interview rehearsal: two design questions (optional)

    Semantic search over 200 million passages, 1,024-d embeddings, 500 queries per second, p99 under 100 ms, per-customer filters, daily updates. Raw vectors: 200M × 4 KB = 819 GB, too much RAM for one node. Options: (1) int8 or RaBitQ codes in RAM (205 GB or about 27 GB) with HNSW or IVF, full vectors on SSD for rescoring the top 100; (2) a DiskANN-style SSD graph with PQ codes in RAM. Shard by customer where customers are large (the filter becomes routing), by hash otherwise, 4 to 8 shards plus replicas for QPS; scatter-gather and merge top k. Filters: pre-filter for small customers, a filter-aware graph for large ones. Updates: write to a small fresh in-memory index, merge into the main one nightly, tombstones for deletes, periodic rebuild. Measure recall against exact search on a sample daily, and answer quality on a labelled set after every change.

    Your RAG answers got worse after switching to a faster index. How do you check whether the index is to blame? Run the same queries through exact search and compare top-k overlap (ANN recall) and the downstream metric; if ANN recall dropped below about 0.9 the index (or its default knob) is the cause; if not, look at chunking, the model, or filters.

    Measured on the topic's shared runs: what the root page used to show (moved here when the root's Vector search lab was retired, 2026-10-24; 1 min)

    Recorded in the root page's src/vec (FAISS 1.15.1 on CPU, one thread for builds, k-means seed fixed; deterministic, no lock), on SciFact's Qwen3-Embedding vectors. ANN recall is not relevance: an HNSW setting that returns 95.9% of the exact top 10 (efSearch 8) finds a labelled relevant abstract in the top 10 for 82.7% of claims, against 84.5% for exact search: the index loses relevant abstracts about as often as any other neighbour, and a perfect index cannot lift retrieval above the model's 84.5%. PQ: distances are estimated from the codes, and the estimate reorders neighbours, which is why a shortlist is rescored. Memory: the formulas of section 11 count vectors and links; real engines add metadata, text and allocator overhead.

    Every measured number on this page comes from the scripts in this page's src/scripts folder, run on an Apple M1 Pro (10 CPU cores, 16 GB) on 2026-10-14 against the running example of Topic: rag-and-retrieval; results in src/data. Library versions: FAISS 1.15.1, hnswlib 0.8.0, Qdrant 1.19.2 (server, Docker), ScaNN 1.4.2 (Linux container), qdrant-client 1.19.1, NumPy 2.5.4. Source quoted at the pinned tags faiss v1.15.1 and hnswlib v0.8.0. Published numbers are labelled and kept apart.