Handbooks  /  The Vector Databases Handbook
Handbook~15 min readIntermediate
Deep Dive

Vector databases,
and approximate nearest neighbors.

Embeddings turn meaning into geometry — but finding the nearest vectors among millions, fast, is its own hard problem. A vector database is the answer: a specialized index that trades a sliver of accuracy for enormous speed. Here's how those indexes actually work.

New to embeddings? Meaning as arrows — the 2-minute visual intro
01

The problem: nearest neighbors at scale

An embedding model maps text (or images) to a vector in a high-dimensional space where similar meanings sit close together. Semantic search, RAG, and recommendations all reduce to one operation: given a query vector, find the stored vectors nearest to it. That's a k-nearest-neighbor (kNN) query.

The naive way — brute force — compares the query against every stored vector and sorts by distance. That's exact, but it costs O(N × d) per query: with millions of vectors of hundreds or thousands of dimensions each, a single search touches billions of numbers. Far too slow for interactive use, and it only gets worse as your corpus grows. A vector database exists to make this fast.

→ The core trade

You can have exact-but-slow (brute force) or approximate-but-fast. Vector databases choose the second: give up a tiny bit of accuracy (you might miss a true neighbor occasionally) to make queries orders of magnitude faster.

02

Distance: what "near" means

"Nearest" needs a distance metric. Three are common, and they must match how your embedding model was trained.

MetricMeasuresUse when
Cosine similarityAngle between vectors (direction, ignoring length)Most text embeddings — meaning is in direction
Dot productDirection and magnitude togetherWhen vector length carries signal; fast on normalized vectors
Euclidean (L2)Straight-line distance in the spaceSome image/embedding spaces; geometric closeness

For most modern text embeddings, vectors are normalized and cosine = dot product, so the choice collapses. The rule: use the metric your embedding model was trained with — mixing metrics quietly wrecks relevance.

03

Approximate nearest neighbor (ANN)

The key idea that makes vector search fast is approximate nearest neighbor search. Instead of guaranteeing the exact top-k, an ANN index cleverly organizes the vectors so a query only has to examine a small, promising subset rather than everything — returning the true neighbors almost always.

Quality is measured by recall: of the true top-k neighbors, what fraction did the index return? An index at 0.98 recall finds 98% of the real neighbors while examining a tiny fraction of the data. Every ANN index exposes knobs that trade recall against latency (and memory): search harder for higher recall but slower, or search less for speed. This recall–latency–memory triangle is the whole game.

04

The index types

Three families dominate. They organize vectors differently, and trade the triangle differently.

HNSW

Graph

A multi-layer proximity graph. Search hops greedily toward the query, coarse layer to fine. Top recall & low latency — but high memory.

IVF

Clustering

Partition vectors into clusters; a query searches only the few nearest clusters. Lower memory, tunable via how many clusters you probe.

PQ

Compression

Product quantization compresses vectors into tiny codes so billions fit in RAM. Slashes memory; costs some recall.

HNSW (Hierarchical Navigable Small World) builds a graph where each vector links to nearby ones across layers; searching greedily walks the graph toward the query, which is remarkably fast and accurate — the default for many stores, at the price of holding the graph in memory. IVF (Inverted File) clusters the space and, per query, only scans the nearest clusters (you tune how many you probe: more = higher recall, slower). Product quantization compresses each vector into a small code, so you can hold vastly more vectors in memory and compare them cheaply — often combined with IVF (IVF-PQ) for billion-scale search. Real systems mix these; the choice depends on your scale, memory budget, and recall target.

05

Filtering by metadata

Real queries aren't pure similarity — you want "nearest chunks where tenant = X and date > last week." So vectors are stored with metadata, and search is filtered. This is subtler than it looks, because the ANN index navigates by geometry, not by your filter.

Post-filtering (retrieve top-k, then drop non-matches) is simple but can return too few results if the filter is selective — the matches might all be past the top-k. Pre-filtering (restrict the search to matching vectors) gives correct results but is harder to do efficiently inside an ANN index. Good vector databases integrate filtering into the index so it's both correct and fast; how well they do it is a key differentiator.

→ The filtering gotcha

Naive post-filtering plus a selective filter can silently return far fewer than k results — the true matches were beyond the top-k the index looked at. Prefer engines with real filtered-ANN support for selective filters.

06

Updates, freshness & consistency

Corpora change: documents are added, updated, deleted. ANN indexes — especially graph-based ones — are optimized for search, not for constant mutation, so handling upserts and deletes efficiently is a real engineering concern. Vectors are typically written to a mutable buffer and periodically merged into the main index; deletes are often soft (marked, later compacted).

This introduces a freshness lag — a just-added vector may not be searchable for a moment — and the usual consistency questions. For search over a slowly-changing knowledge base this is fine; for real-time use you tune the refresh interval. And remember the embedding-consistency rule from RAG: if you change the embedding model, every vector must be re-embedded and the index rebuilt, since vectors from different models aren't comparable.

07

Scaling & hybrid search

Past one machine, vector databases shard the index across nodes and scatter-gather queries: each shard returns its local top-k, and the results are merged. Replicas add read throughput and availability. Because ANN indexes are memory-hungry (especially HNSW), the memory-vs-cost math often drives the architecture — which is exactly where PQ compression earns its keep.

Most production retrieval isn't pure vector search either. Hybrid search fuses vector similarity with keyword/BM25 to catch exact terms (names, codes) that embeddings miss, and pairs with a reranker for precision. A vector database is one component of a retrieval stack, not the whole thing.

08

Do you even need one?

Not every project needs a dedicated vector database. At modest scale — up to a few million vectors — a Postgres extension like pgvector keeps your vectors alongside your relational data and metadata in one system you already run, which is simpler and often plenty fast. Libraries like FAISS give you the raw ANN index in-process with no server at all.

Reach for a dedicated vector database when you hit real scale (tens of millions to billions of vectors), need high query throughput, want advanced filtering and hybrid search out of the box, or require horizontal scaling and operational features you'd otherwise build yourself. Start simple; upgrade when the numbers demand it — not because vector databases are fashionable.

Smallpgvector / FAISS — up to a few million vectors, alongside existing data. Simplest.
LargeDedicated vector DB — tens of millions+, high QPS, filtering, hybrid, horizontal scale.
AlwaysMatch the metric to your embedding model, and re-index when the model changes.
Frequently asked

Quick answers

What is a vector database?

A store for high-dimensional embedding vectors that answers nearest-neighbor queries fast, using approximate-nearest-neighbor indexes. It powers semantic search, RAG, and recommendations over millions or billions of vectors.

Why not brute-force kNN?

Comparing a query to every vector is O(N·d) per query — too slow at millions of high-dimensional vectors. ANN indexes trade a little accuracy for orders-of-magnitude faster search.

HNSW vs IVF vs PQ?

HNSW is a graph index with top recall and low latency but high memory. IVF clusters the space and probes the nearest clusters. PQ compresses vectors to fit billions in RAM. They're often combined (e.g. IVF-PQ).

Dedicated vector DB or pgvector?

For a few million vectors, pgvector alongside Postgres is often enough. Go dedicated at large scale, high throughput, or when you need advanced filtering, hybrid search, and horizontal scaling.

Finished this one? 0 / 29 Handbooks done

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.