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
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.
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).
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.
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.
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.
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.
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.
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).
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.
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.
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.
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
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).
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.
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:
| Family | What is stored per vector | bytes (d = 1,024) | How distance is computed |
|---|---|---|---|
| float16 | each number in 16 bits | 2,048 | as float32, after conversion |
| Scalar int8 (SQ8) | each number mapped to 0..255 within its learned range | 1,024 | on decoded values |
| Scalar int4 (SQ4) | each number in 4 bits | 512 | on decoded values |
| Binary | the sign of each number, 1 bit | 128 | Hamming distance (count differing bits) |
| RaBitQ | 1 bit per dimension after a random rotation, plus a few floats | 136 | an unbiased estimator with an error bound |
| Product quantization (PQ), m sub-vectors | m one-byte ids of learned sub-vector centroids | m (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.
Leaving the query unquantized is asymmetric distance computation (ADC), which the paper shows beats quantizing the query too.
"For m=8 we obtain the same accuracy for ADC and k*=64 as for SDC and k*=256" (Section V, published, authors' runs).
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.
Which model tolerates quantization, and Matryoshka truncation, belong to Embedding models.
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).
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?
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.
For inner product the score splits into the coarse term and the table term; for L2 FAISS adds the third term it can precompute.
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.
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 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.
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:
Three details that the paper's prose does not make obvious and the code does:
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.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:
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).
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: 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 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).
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).
"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:
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.
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.
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.
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).
| Strategy | How | Fails when |
|---|---|---|
| Pre-filter | find the passing rows with an ordinary index (B-tree, bitmap), then exact search over them | the filter keeps many rows (then it is a big exact scan) |
| Post-filter | ANN search for k′ > k results, drop those that fail | the filter is selective or anti-correlated: few of the k′ pass |
| In-graph filter | walk the graph as usual, but only passing nodes enter the results | selective filters: the walk must visit most of the graph to collect k passing nodes |
| Predicate-aware graph | walk only (or mostly) through passing nodes, with extra links so they stay connected: ACORN, Qdrant's payload links, Filtered-DiskANN | build 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.
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.
Measured on the topic's data measured here; ef = 100, k′ = 100 unless stated; "distances" is the work per query:
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.
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.
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.
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).
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 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.
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.
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:
| Index | Bytes, approximately | Where the terms come from |
|---|---|---|
| Flat | N · d · b | the vectors |
| IVF-Flat | N · (4d + 8) + nlist · 4d | vectors and 8-byte ids in the lists; centroids |
| IVF-PQ | N · (m + 8) + nlist · 4d + 256 · 4d | codes and ids; centroids; PQ codebooks |
| hnswlib HNSW | N · (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 IndexHNSWFlat | N · 4d + N · 4 · (2M + M/(M−1)) + N · 12 | vectors (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.
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).
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.
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:
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.
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.
| Situation | Start with | Why (evidence on this page) |
|---|---|---|
| Under about 50,000 vectors, or queries in batches | Flat (exact), maybe float16 | 2.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 often | HNSW, M 16 to 32, efConstruction 100 to 200, ef tuned per query | 0.993 recall at 0.19 ms on 522,931 vectors (Frontier); inserts any time (section 6) |
| RAM is tight | HNSW or IVF over int8 (4× smaller), or IVF-PQ / RaBitQ with rescoring | int8 keeps recall 0.995; 1-bit RaBitQ with rescoring 1.000 (section 4) |
| Hundreds of millions to billions | IVF-PQ with a graph over the centroids, or DiskANN / SPANN on SSD, sharded | Big-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) above | crossover near 10 to 25% here (section 9) |
| Data mostly static, build time no object | a graph built with care (Vamana, NSG), or IVF with many cells | section 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).
| System (version) | What | Value | Source |
|---|---|---|---|
| hnswlib 0.8.0 | HNSW M / efConstruction / ef | 16 / 200 / 10 | Python binding defaults; hnswalg.h line 115 (ef_ = 10) |
| FAISS 1.15.1 IndexHNSWFlat | M / efConstruction / efSearch | (you pass it; 32 is common) / 40 / 16 | impl/HNSW.h lines 141 and 144 |
| FAISS 1.15.1 IndexIVF | nprobe | 1 | IndexIVF.h line 69 |
| FAISS | RaBitQ | in FAISS by 1.11.0, 2025-04-24 | CHANGELOG |
| pgvector 0.8.7 | m / ef_construction / ef_search | 16 / 64 / 40 | README (Search and vector databases page) |
| Lucene (main) | M / beam width / query | 16 / 100 ("beam width") / set per query | HnswGraphBuilder.java |
| Elasticsearch 9.x | m / ef_construction / query | 16 / 100 / num_candidates | dense_vector docs (vendor docs) |
| Qdrant 1.19 | m / ef_construct / query | 16 / 100 / hnsw_ef | indexing docs (vendor docs) |
| Qdrant | ACORN-1 search | opt-in from v1.16.0 (2025-11-17) | release notes |
| Weaviate 1.40 | maxConnections / efConstruction / ef | 32 (64 on layer 0) / 128 / dynamic (100 to 500) | vector index docs (vendor docs) |
| Weaviate | ACORN filter strategy | added in v1.27, the default in v1.34 | filtering docs |
| Milvus 3.0 | HNSW M / efConstruction / query | 30 / 360 / ef | HNSW docs (vendor docs) |
| Milvus 3.0 | DISKANN | MaxDegree 56, SearchListSize 100, PQCodeBudgetGBRatio 0.125, BeamWidthRatio 4 | DISKANN docs (vendor docs) |
| DiskANN | official code | diskannpy 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 Vamana | DiskANN-style indexes | Azure's pg_diskann and Cosmos DB, SQL Server 2025, Timescale's pgvectorscale (StreamingDiskANN), Redis 8.2's SVS-VAMANA | dates and links on the Search and vector databases page and the parent's Tool map |
| ScaNN in products | AlloyDB's alloydb_scann; Vertex AI Vector Search is built on it | Search and vector databases page |
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.
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 index family on this page, each swept over its query-time knob, timed on the same machine the same way: one CPU thread, one query at a time, three passes over the query set (median of each pass, median of the three). Up and right is better. The outlined points form the Pareto frontier: no other setting is both faster and more accurate. Lower the memory budget and watch which families survive.
Recall, speed and memory for every family, timed; lower the memory budget and see which survive. 5 min
The whole pipeline; its Tool map tab (what each store and library actually runs, measured defaults). 19 min
Where the vectors come from; Matryoshka, int8 and binary from the model's side. 30 min
Chunking, hybrid search, metadata filtering from the pipeline's side. 47 min
The exact second stage after the index; ColBERT's token vectors. 34 min
Tenants, access control, re-indexing and latency budgets. 37 min
What gets embedded in the first place. 28 min
The database-engine view: pgvector's HNSW and IVFFlat inside PostgreSQL, iterative scans, VACUUM, halfvec and binary indexes, measured on the same Quora vectors. 27 min
Storage engines, indexes and transactions around the vectors. 29 min
Judged metrics, beyond the recall this page counts. 27 min
Dot products, norms, rotations (OPQ), projections. 45 min
The same number formats applied to model weights. 34 min
Layers, the heuristic, parameter advice (Section 4). 60 min
ADC, SDC, IVFADC. 60 min
Vamana, RobustPrune, the SSD layout. 45 min
Predicate subgraph traversal. 45 min
Score-aware quantization loss. 40 min
1-bit codes with an error bound. 45 min
Flat graphs match HNSW in high dimensions; hubs. 30 min
Every index family in one framework, with a decision tree. 60 min
Streaming inserts and deletes on a graph index. 40 min
Billion scale with posting lists on SSD. 35 min
Independent billion-scale and filtered, streaming, sparse benchmarks. 40 min
The whole algorithm in one header; read with section 6 beside it. 45 min
IndexIVF.cpp, impl/ProductQuantizer.cpp, impl/HNSW.cpp. 60 min
The string names (IVF4096,PQ64 and so on). 15 min
Independent recall against QPS for many libraries, single CPU, up to about 10M vectors. 15 min
Payload links, the query planner, thresholds. 15 min
Rules of thumb for partitioning, AH and reordering. 10 min