AS·160
Vector Databases
Storing and searching millions to billions of embeddings fast: why exact search stops scaling, approximate nearest-neighbour search and the recall–latency–memory trade-off, HNSW graphs (navigable small worlds, layers, M, efConstruction, efSearch) with a working graph search, IVF partitioning with nprobe, product quantisation and scalar/binary quantisation with rescoring, DiskANN for SSD-resident indexes, metadata filtering (pre-, post- and in-filtering) and multi-tenancy, hybrid dense + sparse retrieval with reciprocal rank fusion, updates and deletes, consistency and operations, and a practical tour of pgvector, Qdrant, Milvus, Weaviate, Elasticsearch/OpenSearch, Redis, FAISS and managed stores, with code in SQL, Python, Java, Go, Rust and TypeScript.
Start here: finding the nearest vectors quickly
Chapter 159 turned text into vectors. To answer a question you need the stored vectors closest to the question's vector. With a few thousand vectors you can simply compare against every one. With millions you can't, and that is the job of a vector database (or a vector index inside an ordinary database).
Why comparing against everything stops working
Ten million documents with 1,024-number embeddings take about 41 GB as 32-bit floats, and one exact search multiplies the question against all of them: roughly 20 billion multiply-adds per query. That's fine for a nightly job and far too slow for a chat reply at hundreds of queries per second.
The trick: search approximately
An approximate nearest-neighbour (ANN) index gives up a little accuracy for a lot of speed. Two ideas dominate:
- Graphs (HNSW): link each vector to a few close neighbours; a search hops from neighbour to neighbour towards the question, like asking for directions in a city where everyone knows their neighbours.
- Partitions (IVF): group vectors into clusters ahead of time; a search looks only inside the few clusters nearest the question.
Their quality is measured by recall@k: of the true 10 nearest vectors, how many did the index return? The lab measured both on 200,000 vectors: exact search took about 20 ms per query, while a well-tuned HNSW index answered in a fraction of a millisecond with recall close to 1.
What a vector database adds around the index
Storing the text and metadata with each vector, filtering ("only this customer's documents"), updates and deletes, replication and backups, and usually keyword search too. Those everyday features, filtering especially, are where the hard problems live.
How deep to go in vector databases
Volume 17 defines six mastery levels; for vector databases they look like this:
| Level | You can… |
|---|---|
| L1 | explain exact vs approximate search and recall@k |
| L2 | create an index, insert vectors with metadata, and query with filters |
| L3 | explain HNSW, IVF and product quantisation and their parameters |
| L4 | diagnose low recall, slow queries, filter starvation and memory blow-ups |
| L5 | choose an index and a database for a workload, with measured recall/latency/memory |
| L6 | operate vector search at scale: sharding, replication, re-indexing, multi-tenancy, cost |
Why a vector database
Chapter 159's exact search computes a similarity with every vector: O(N·d) per query. At 100 million vectors of 768 dimensions that's 77 billion multiply-adds per query: far too slow for interactive search at many queries per second. A vector database (or vector index inside an existing database) provides:
- Approximate nearest-neighbour (ANN) indexes: sub-linear search with tunable accuracy.
- Storage of vectors with ids, payloads and metadata; CRUD; persistence and replication.
- Filtering by metadata (tenant, language, date, access rights) combined with vector search.
- Hybrid search combining dense vectors with keyword (sparse) retrieval.
- Operational features: sharding, backups, snapshots, monitoring, access control.
Measuring ANN quality
ANN indexes are judged on three axes at once:
- Recall@k: fraction of the true k nearest neighbours (from exact search) that the index returns. 0.95–0.99 is typical.
- Latency / throughput: p50/p99 query latency, queries per second.
- Memory and build cost: bytes per vector including index overhead; index build time; update cost.
Every index exposes parameters that move along this frontier. Benchmarks (ANN-Benchmarks, VectorDBBench) plot recall vs QPS; always measure on your data and filters.
HNSW: hierarchical navigable small-world graphs
HNSW (Malkov and Yashunin, 2016) is the most widely used ANN index.
Navigable small worlds
Build a graph where each vector is a node linked to some of its nearest neighbours (plus a few longer links). Greedy search: start from an entry point; repeatedly move to whichever neighbour is closer to the query; stop when no neighbour is closer. Small-world structure means a few hops reach any region.
Greedy search with a single candidate can get stuck in a local minimum, so search keeps a dynamic candidate list of size ef (beam search over the graph): larger ef = higher recall, slower.
The hierarchy
HNSW adds layers like a skip list: every node is in layer 0; a random, exponentially decreasing fraction also appears in layers 1, 2, …. Upper layers are sparse with long links (fast coarse navigation); lower layers are dense (fine search). Search starts at the top entry point, greedily descends layer by layer, and runs the ef-wide search on layer 0.
Parameters
| Parameter | Meaning | Effect |
|---|---|---|
| M | Max links per node (layer 0 often 2M) | Higher → better recall, more memory (≈ M × 2 × 4–8 bytes per vector), slower build |
| efConstruction | Candidate list size while inserting | Higher → better graph quality, slower build |
| efSearch (ef) | Candidate list size at query time (≥ k) | The main recall/latency knob, tunable per query |
Typical: M = 16–32, efConstruction = 100–400, efSearch = 40–200. HNSW is fast and accurate but memory-hungry (vectors plus graph in RAM), supports incremental inserts, and handles deletes with tombstones and periodic repair.
Greedy graph search, from scratch
A single-layer navigable graph with beam search shows the core mechanism:
import numpy as np, heapq
rng = np.random.default_rng(0)
N, d = 5000, 32
X = rng.normal(size=(N, d)); X /= np.linalg.norm(X, axis=1, keepdims=True)
def build_knn_graph(X, M=12, sample=None):
"""Link each node to its M nearest neighbours (exact here; HNSW builds this incrementally)."""
sims = X @ X.T
np.fill_diagonal(sims, -np.inf)
return np.argpartition(-sims, M, axis=1)[:, :M]
def beam_search(q, X, graph, entry, ef=32, k=10):
dist = lambda i: -float(X[i] @ q) # smaller = closer (negative cosine)
visited = {entry}
candidates = [(dist(entry), entry)] # min-heap: closest first
best = [(-dist(entry), entry)] # max-heap of current best ef
while candidates:
dc, c = heapq.heappop(candidates)
if dc > -best[0][0] and len(best) >= ef: break # closest candidate worse than worst kept
for nb in graph[c]:
if nb in visited: continue
visited.add(nb); dn = dist(nb)
if len(best) < ef or dn < -best[0][0]:
heapq.heappush(candidates, (dn, nb)); heapq.heappush(best, (-dn, nb))
if len(best) > ef: heapq.heappop(best)
return [i for _, i in sorted((-s, i) for s, i in best)][:k], len(visited)
graph = build_knn_graph(X)
queries = rng.normal(size=(50, d)); queries /= np.linalg.norm(queries, axis=1, keepdims=True)
for ef in (10, 40, 160):
recalls, visits = [], []
for q in queries:
truth = set(np.argsort(-(X @ q))[:10])
found, n_visited = beam_search(q, X, graph, entry=0, ef=ef)
recalls.append(len(truth & set(found)) / 10); visits.append(n_visited)
print(ef, round(np.mean(recalls), 2), int(np.mean(visits)))
# ef=10 → recall ≈ 0.37 (163 visited) · ef=40 → 0.79 (447) · ef=160 → 0.97 (1,266 of 5,000)
Real HNSW adds the layers (for a good entry point instead of node 0), heuristic neighbour selection that keeps diverse links, and incremental construction.
IVF: inverted file indexes
IVF partitions the space with k-means (chapter 148) into nlist clusters. Each vector is stored in the list of its nearest centroid. At query time, compare the query with the centroids and search only the nprobe closest lists.
- nlist ≈ √N to 4√N is a common starting point; nprobe controls recall vs speed.
- Less memory overhead than HNSW; builds need a training step on a representative sample; works well combined with compression (IVF-PQ) and on GPUs.
- Vectors near cluster boundaries may be missed unless nprobe is large enough.
Compression: quantisation
| Technique | Size per 768-dim vector | Idea |
|---|---|---|
| float32 | 3,072 B | Baseline |
| float16 / bfloat16 | 1,536 B | Half precision, negligible recall loss |
| Scalar int8 | 768 B | Map each dimension's range to 256 levels |
| Binary | 96 B | 1 bit per dimension (sign); Hamming distance; works well for high-dimensional models, with rescoring |
| Product quantisation (PQ) | e.g. 96 B (m = 96 sub-vectors × 1 byte) | Split vector into m sub-vectors; k-means each subspace into 256 centroids; store centroid ids; distances via precomputed lookup tables |
Rescoring recovers accuracy: search the compressed index for, say, 4×k candidates, then recompute exact similarities using full-precision vectors (stored on disk or in a cheaper tier) and re-sort.
def train_pq(X, m=8, ks=256, iters=10):
"""Product quantisation: m subspaces, ks centroids each."""
n, d = X.shape; ds = d // m; books = []
for j in range(m):
sub = X[:, j * ds:(j + 1) * ds]
C = sub[rng.choice(n, ks, replace=False)]
for _ in range(iters):
a = ((sub[:, None] - C[None]) ** 2).sum(-1).argmin(1)
C = np.array([sub[a == c].mean(0) if np.any(a == c) else C[c] for c in range(ks)])
books.append(C)
return books
def pq_encode(X, books):
m = len(books); ds = X.shape[1] // m
return np.stack([((X[:, j*ds:(j+1)*ds][:, None] - books[j][None]) ** 2).sum(-1).argmin(1)
for j in range(m)], axis=1).astype(np.uint8) # [n, m] bytes
def pq_scores(q, codes, books):
m = len(books); ds = len(q) // m
tables = np.stack([books[j] @ q[j*ds:(j+1)*ds] for j in range(m)]) # [m, 256] partial dot products
return tables[np.arange(m), codes].sum(1) # asymmetric distance: sum of lookups
books = train_pq(X, m=8, ks=256)
codes = pq_encode(X, books) # 8 bytes per vector instead of 128
q = queries[0]
truth = set(np.argsort(-(X @ q))[:10])
cand = np.argsort(-pq_scores(q, codes, books))[:100] # coarse search on codes
rescored = cand[np.argsort(-(X[cand] @ q))][:10] # exact rescoring of 100 candidates
len(truth & set(np.argsort(-pq_scores(q, codes, books))[:10])) / 10, len(truth & set(rescored)) / 10 # ≈ 0.4 from codes alone, 1.0 after rescoring
DiskANN / Vamana (Microsoft) builds a graph designed for SSD access: compressed vectors in RAM guide the search, full vectors and graph live on SSD; billion-scale on one machine with modest RAM. Several databases offer DiskANN-style or on-disk HNSW indexes.
Metadata filtering
Real queries combine similarity with constraints: "documents for tenant 42, in English, updated after 2026-01-01, that this user may read".
| Strategy | How | Problem |
|---|---|---|
| Post-filtering | ANN search for top-k, then drop non-matching results | With selective filters, few or zero results survive; must over-fetch |
| Pre-filtering | Compute the matching id set first, then search only those (exact search if small) | Graph indexes don't naturally restrict traversal; brute force over large matching sets is slow |
| Filtered / in-graph search | Traverse the index while skipping non-matching nodes, with extra links or adaptive strategies to stay connected | Implemented by most modern vector DBs (Qdrant, Weaviate, Milvus, pgvector iterative scans) |
Multi-tenancy: per-tenant collections or partitions (strong isolation, many small indexes) vs one shared index with a tenant filter (efficient, but filter correctness is a security boundary: always enforce tenant and access filters server-side, never from the LLM or client).
Hybrid retrieval
Dense embeddings capture meaning but can miss exact terms: product codes ("XR-2291"), names, rare jargon, error messages. Sparse lexical retrieval (BM25, chapter 161; or learned sparse models such as SPLADE) excels there. Hybrid search runs both and fuses the results.
Reciprocal rank fusion (RRF) combines ranked lists without calibrating scores:
RRF(d) = Σ over lists 1 / (k + rank_list(d)), k ≈ 60
def rrf(*ranked_lists, k=60):
scores = {}
for lst in ranked_lists:
for rank, doc in enumerate(lst, start=1):
scores[doc] = scores.get(doc, 0.0) + 1.0 / (k + rank)
return sorted(scores, key=scores.get, reverse=True)
dense = ["d3", "d1", "d7", "d4"] # semantic matches
sparse = ["d9", "d3", "d4", "d2"] # exact keyword matches (e.g. the product code)
rrf(dense, sparse) # ['d3', 'd4', 'd9', 'd1', 'd7', 'd2']: agreement rises to the top
Alternatives: weighted score fusion after normalising scores; a cross-encoder reranker over the union (chapter 161).
Updates, consistency and operations
- Inserts are cheap in HNSW-style indexes; updates are delete + insert; deletes are usually tombstones cleaned by background compaction/optimisation. Heavy churn degrades graph quality until rebuilt.
- Freshness: many systems buffer writes in a small, brute-force-searched segment before merging into the main index (LSM-like), making new data searchable quickly.
- Consistency: replicas may lag; read-your-writes may need explicit options.
- Capacity planning: RAM for vectors (unless quantised/on disk) + graph + payload indexes; plan headroom for rebuilds.
- Backups and re-indexing: keep the source text and metadata as the system of record; vectors can be regenerated (chapter 159's re-embedding).
- Observability: query latency percentiles, recall audits against exact search on samples, index size, memory, filter selectivity.
Technologies
| System | Type | Highlights |
|---|---|---|
| pgvector | PostgreSQL extension (0.8.x line in 2025–2026) | vector, halfvec, bit and sparsevec types; HNSW and IVFFlat indexes; distance operators; iterative index scans for filtered queries; transactions, joins and SQL filters with your relational data. Often the right first choice when you already run Postgres |
| Qdrant | Rust vector database | Payload filtering integrated into HNSW, quantisation (scalar, binary, product), sparse vectors and hybrid queries, multitenancy, on-disk storage |
| Milvus / Zilliz | Distributed vector database (Go/C++) | Many index types (HNSW, IVF variants, DiskANN, GPU indexes), separation of storage and compute, billion scale |
| Weaviate | Go vector database | Built-in vectorisation modules, hybrid BM25 + vector search, multi-tenancy, GraphQL/REST/gRPC |
| Elasticsearch / OpenSearch | Search engines with dense vector fields | Mature BM25 + kNN hybrid, filters and aggregations; good if search infra exists |
| Redis, MongoDB Atlas Vector Search, Cassandra/Astra, SQL Server/Oracle/MySQL vector types | Vector search in existing databases | Fewer moving parts |
| FAISS (Meta) | Library (C++/Python, GPU) | The reference ANN toolkit; no database features |
| LanceDB, Chroma, sqlite-vec | Embedded / lightweight | Local apps, prototypes, edge |
| Managed | Pinecone, cloud vector search services (e.g. on AWS, Google Cloud, Azure), provider-hosted vector stores | No operations; check cost at scale, filtering semantics and data residency |
-- PostgreSQL + pgvector: vectors next to relational data
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE chunks (
id bigserial PRIMARY KEY,
tenant_id int NOT NULL,
doc_id bigint NOT NULL REFERENCES documents(id),
content text NOT NULL,
embedding vector(768) NOT NULL,
model text NOT NULL DEFAULT 'embed-v3'
);
CREATE INDEX ON chunks USING hnsw (embedding vector_cosine_ops) WITH (m = 16, ef_construction = 200);
CREATE INDEX ON chunks (tenant_id);
SET hnsw.ef_search = 100;
SET hnsw.iterative_scan = relaxed_order; -- keep scanning when filters remove results
SELECT id, content, 1 - (embedding <=> $1) AS cosine_similarity
FROM chunks
WHERE tenant_id = $2
ORDER BY embedding <=> $1 -- <=> cosine distance, <-> L2, <#> negative inner product
LIMIT 10;
# Python: Qdrant client — collection with HNSW + int8 quantisation, filtered search
from qdrant_client import QdrantClient, models
client = QdrantClient(url="http://localhost:6333")
client.create_collection("chunks",
vectors_config=models.VectorParams(size=768, distance=models.Distance.COSINE),
quantization_config=models.ScalarQuantization(scalar=models.ScalarQuantizationConfig(type=models.ScalarType.INT8)))
client.upsert("chunks", points=[models.PointStruct(id=1, vector=vec, payload={"tenant": 42, "lang": "en"})])
hits = client.query_points("chunks", query=qvec, limit=10,
query_filter=models.Filter(must=[models.FieldCondition(key="tenant", match=models.MatchValue(value=42))])).points
# Python: FAISS as a library — IVF-PQ index
import faiss
quantizer = faiss.IndexFlatIP(d)
index = faiss.IndexIVFPQ(quantizer, d, 1024, 16, 8) # nlist=1024, m=16 sub-vectors, 8 bits
index.train(train_vectors); index.add(vectors)
index.nprobe = 16
D, I = index.search(query_vectors, 10)
// Java: Spring AI VectorStore abstraction (PgVector, Qdrant, Milvus, Weaviate, Redis, ...)
List<Document> hits = vectorStore.similaritySearch(SearchRequest.builder()
.query("how do I rotate API keys?")
.topK(8)
.similarityThreshold(0.5)
.filterExpression("tenant == 42 && lang == 'en'")
.build());
// Go: pgvector-go with pgx
rows, err := conn.Query(ctx,
"SELECT id, content FROM chunks WHERE tenant_id = $1 ORDER BY embedding <=> $2 LIMIT 10",
tenantID, pgvector.NewVector(queryEmbedding))
// Rust: qdrant-client
let res = client.query(QueryPointsBuilder::new("chunks")
.query(query_vec)
.filter(Filter::must([Condition::matches("tenant", 42)]))
.limit(10)).await?;
Choosing
- Already on Postgres and below tens of millions of vectors? Start with pgvector: one system, transactions, SQL joins and filters, backups you already have.
- Heavy filtering, hybrid search, quantisation at scale, high QPS? A dedicated vector database (Qdrant, Milvus, Weaviate) or your search engine (Elasticsearch/OpenSearch).
- Billions of vectors or tight memory budgets? IVF-PQ, DiskANN-style indexes, binary quantisation with rescoring.
- No ops capacity? Managed services, after checking cost curves and data-governance requirements.
- Whatever you choose: benchmark recall and latency with your filters, keep source data as the system of record, and store model versions with vectors.
Lab: recall, latency and memory of real ANN indexes
Setup. faiss-cpu 1.15.1 and hnswlib on the lab machine (2 vCPUs). Data, a stated substitute: 200,000 synthetic 256-dimensional unit vectors drawn around 2,000 random cluster centres with heavy noise, so clusters overlap the way topics do in real embeddings; 1,000 queries drawn the same way. Ground truth is exact search; recall@10 is the overlap with it. Latency is one query at a time, averaged over 300 queries. Real embeddings have different structure, so rerun this on your own vectors before choosing parameters.
Experiment 1: exact search
| memory (float32) | 205 MB |
| one query at a time | 21 ms |
| batched (1,000 queries) | 2.0 ms per query |
Exact search is perfectly accurate and needs no build, and at this scale it is already too slow for interactive use at high request rates. Batching helps throughput, not the latency of one user's query.
Experiment 2: HNSW
| M | efSearch | Build | recall@10 | ms / query | Index file |
|---|---|---|---|---|---|
| 8 | 16 | 42 s | 0.348 | 0.045 | 222 MB |
| 8 | 64 | 0.777 | 0.157 | ||
| 8 | 256 | 0.985 | 0.527 | ||
| 16 | 16 | 69 s | 0.808 | 0.110 | 235 MB |
| 16 | 64 | 0.999 | 0.249 | ||
| 16 | 256 | 1.000 | 0.903 |
- efSearch is the query-time dial: larger means more of the graph explored, higher recall and more latency. It can be changed per query without rebuilding.
- M (links per node) is the build-time dial: more links cost build time and memory but reach high recall with less search effort. M = 16, ef = 64 found 99.9% of the true neighbours 84× faster than exact search.
- The index holds the full vectors plus the graph: HNSW saves time, not memory.
Experiment 3: IVF and product quantisation
| Index | nprobe | recall@10 | ms / query | Memory |
|---|---|---|---|---|
| IVF 1,024 lists, flat | 1 | 0.797 | 0.048 | ≈ full vectors |
| 8 | 0.830 | 0.415 | ||
| 32 | 0.868 | 0.582 | ||
| 128 | 0.930 | 2.414 | ||
| IVF 1,024 + PQ (32 × 8-bit codes) | 8 | 0.413 | 0.064 | 9 MB |
| 32 | 0.433 | 0.152 | ||
| PQ top 100, reranked with exact vectors | 32 | 0.867 | 9 MB + vectors on disk |
- On this data IVF needed many probes to approach HNSW's recall: neighbours of a query often sat in other clusters. How well IVF does depends on how well the data clusters; measure it.
- Product quantisation compressed each 1,024-byte vector to 32 bytes (1/32), so 200,000 vectors fit in 9 MB, but alone it ranked poorly. Fetching 100 candidates and reranking with full-precision vectors (from disk or a cheaper tier) recovered most of the recall. This compress-then-rerank pattern is how billion-scale systems fit in memory.
Experiment 4: filtering, the hard part
Each vector got a tenant number (100 tenants, so a tenant owns 1% of the data); queries ask for one tenant's 10 nearest.
| Approach | recall@10 | Note |
|---|---|---|
| HNSW top 10, then filter | 0.006 | 0.06 results returned on average: filter starvation |
| HNSW top 1,000 (ef = 1,000), then filter | 0.548 | far more work, still misses half |
| IVF with the filter inside the search, nprobe 8 / 32 / 128 | 0.165 / 0.295 / 0.546 | the tenant's nearest vectors are spread over many lists |
| a separate exact index per tenant (1,890 vectors) | 1.000 | 0.018 ms |
Post-filtering a selective filter fails badly. Fixes, in order of preference: partition by tenant (a namespace, collection or index per tenant) when the filter is always present; filter-aware search where the database supports it (filtered HNSW traversal, which keeps exploring until enough matches are found); and for very selective filters, exact search over the filtered subset, which is cheap because the subset is small. Good vector databases choose between these automatically from the filter's selectivity; check that yours does, with a test like this one.
Try it yourself
- Rerun Experiment 2 with your own embeddings (or chapter 159's 5,346 LSA vectors). Do the same parameters give the same recall?
- Measure HNSW recall after deleting 30% of the vectors and inserting new ones.
- Add
pgvectorto PostgreSQL and compare its HNSW recall and latency with hnswlib at matched parameters. - For a 0.1% filter, find the selectivity at which exact search over the subset beats filtered HNSW.
Revision sheet: vector databases
Key ideas
- Exact search costs vectors × dimensions per query; ANN trades recall for speed; measure recall@k against exact results.
- HNSW: layered proximity graph; M (links per node; build time, memory, recall), efConstruction (build quality), efSearch (query-time recall/latency dial). Fast and accurate; memory-hungry.
- IVF: k-means partitions; nlist and nprobe trade recall for speed; works best when data clusters well.
- PQ / scalar / binary quantisation: compress vectors; rerank candidates with full vectors to recover recall.
- DiskANN-style indexes keep the graph and compressed vectors in memory and full vectors on SSD.
- Filtering: post-filtering starves selective filters; use partitioning, filter-aware traversal, or exact search on small subsets.
- Operations: upserts and deletes (tombstones, compaction), re-indexing on model change, replication, backups, per-tenant isolation.
- Options: pgvector, Elasticsearch/OpenSearch, Qdrant, Weaviate, Milvus, Pinecone, Vespa, LanceDB, FAISS as a library.
Numbers to remember
- Lab: exact 21 ms/query on 200k × 256; HNSW M=16 ef=64 recall 0.999 at 0.25 ms.
- Lab: PQ 1/32 size, recall 0.43; with exact rerank of top 100, 0.87.
- Lab: post-filtering a 1% tenant filter: recall 0.006; per-tenant index: 1.0.
- Memory: N × d × 4 bytes for float32 vectors, plus graph links (≈ M × 2 × 4 bytes per vector at layer 0).
Pitfalls
- Reporting latency without recall (or recall without latency).
- Tuning on random vectors and deploying on real embeddings (or the reverse).
- Post-filtering selective metadata filters.
- Forgetting that HNSW needs the full vectors in RAM.
- Not budgeting re-indexing time when changing embedding models.
Glossary
- ANN: approximate nearest-neighbour search.
- HNSW: hierarchical navigable small-world graph index.
- IVF: inverted-file index over k-means partitions.
- PQ: product quantisation; vectors split into sub-vectors, each replaced by a codebook index.
- Filter starvation: too few results left after post-filtering.