Skip to content
ML to LLMs
Cheat sheets

Vector search

Similarity metrics, exact vs approximate nearest-neighbor indexes, their knobs and memory, hybrid search with RRF, and filtering pitfalls.

Metrics: dot q⋅xq \cdot x, cosine q⋅x∥q∥∥x∥\frac{q \cdot x}{\lVert q\rVert\lVert x\rVert}, L2 ∥q−x∥\lVert q - x\rVert. For unit vectors all three rank the same (∥q−x∥2=2−2cos⁡\lVert q - x\rVert^2 = 2 - 2\cos), so normalize and use dot. Otherwise use the metric the model was trained with.

IndexHow it worksKnobsCost / memoryUse when
Exact (flat)compare with every vectornoneO(N⋅d)O(N \cdot d) per query; 4Nd4Nd bytes in float32up to a few hundred thousand vectors, small filtered subsets, ground truth
IVFk-means cells, scan nearest nproben_{\text{probe}}nlistn_{\text{list}} (start near N\sqrt{N}), nproben_{\text{probe}}(nlist+nprobenlistN) d(n_{\text{list}} + \frac{n_{\text{probe}}}{n_{\text{list}}}N)\,dlarge NN, cheap build, works with PQ
HNSWlayered neighbor graph, greedy descentMM, efConstruction, efSearch (≥k\ge k)vectors + about 2M×42M \times 4 bytes/vector of linksfits in RAM, want high recall at low latency
PQmm subvectors, each a 1-byte codebook IDmm, codebook size (256)mm bytes/vector (e.g. 3 KB to 96 B, 32×32\times)memory-bound; re-score top candidates exactly

Index recall@k =∣ANN top-k∩exact top-k∣/k= |\text{ANN top-}k \cap \text{exact top-}k| / k. Measure on real queries; tune for a recall target at a latency budget.

Reciprocal rank fusion: RRF(d)=∑j160+rankj(d)\text{RRF}(d) = \sum_j \frac{1}{60 + \text{rank}_j(d)}. Dense A,B,C,D + BM25 E,F,A,B gives A, B, E, F, C, D.

Watch out

Post-filtering a top-kk list keeps about k×k \times selectivity results (0.2 of 10 at 2%). Filter inside the search, partition by tenant, or brute-force small subsets. Enforce access control in retrieval, never in the LLM.

Operations: store model name and version with every vector; re-embed everything when the model changes (blue-green); HNSW deletes are tombstones until rebuild; IVF centroids go stale after heavy inserts.

Where to run it: in-memory (NumPy, FAISS) for small or batch; pgvector when data and metadata already live in Postgres; a dedicated vector database or search engine for scale, hybrid search, and multi-tenancy.

Lessons: Vector search · The RAG pipeline