FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Vector Search

How embeddings similarity indexes filters and recall tradeoffs retrieve semantic candidates.

Freshness: current•15 min read•Retrieval and Knowledge Systems

Key Learning Outcomes

  • ✓Select similarity and index options
  • ✓Use metadata filters
  • ✓Measure retrieval recall
Full Technical Reference Document

Mental model

Vector search embeds queries and documents into a shared dense metric space, then traverses an approximate nearest-neighbor (ANN) structure—typically a Hierarchical Navigable Small World (HNSW) graph—to locate top-kk candidates in O(log⁡N)O(\log N) expected hops instead of scanning every vector linearly. Production recall depends on balancing graph degree, search beam width, vector quantization error, and metadata filter selectivity.

Query embedding
Metadata selectivity check
HNSW upper-layer skip
Layer-0 efSearch beam
Quantized rescore and exact rerank
Conceptual teaching model synthesized from:Sentence-BERT Sentence Embeddings using Siamese BERT-Networkspgvector DocumentationEfficient and robust approximate nearest neighbor search using Hierarchical Navigable Small World graphsProduct Quantization for Nearest Neighbor Search

Theory

Exact kk-nearest-neighbor (kk-NN) search computes NN vector distances per query, scaling at O(N⋅d)O(N \cdot d) floating-point operations and saturating memory bandwidth once collections cross a few hundred thousand high-dimensional chunks. When embeddings are L2-normalized (∥u^∥2=∥v^∥2=1\|\hat{u}\|_2 = \|\hat{v}\|_2 = 1), Euclidean squared distance, cosine distance, and inner product collapse to a single monotonic ordering:

∥u^−v^∥22=2−2(u^⋅v^)=2(1−cos⁡(u^,v^))\|\hat{u} - \hat{v}\|_2^2 = 2 - 2(\hat{u} \cdot \hat{v}) = 2(1 - \cos(\hat{u}, \hat{v}))

Approximate nearest-neighbor indexes eliminate full scans by accepting a controlled probability of missing true neighbors. Hierarchical Navigable Small World (HNSW) generalizes probabilistic skip lists into multi-layer proximity graphs. Each inserted vector receives a maximum layer ℓ=⌊−ln⁡(U)⋅mL⌋\ell = \lfloor -\ln(U) \cdot m_L \rfloor where U∼Uniform(0,1)U \sim \text{Uniform}(0, 1) and mL=1/ln⁡(M)m_L = 1 / \ln(M). Upper layers contain exponentially sparser long-range highway edges; Layer 0 holds every vector with up to Mmax⁡0=2MM_{\max 0} = 2M bidirectional connections. Querying begins at the global entry point on the top layer, performs greedy local descent until no neighbor improves distance, then drops to the next layer using that local optimum as the new seed. At Layer 0, HNSW switches from greedy single-path descent to a dynamic priority queue of width efSearch (≥k\ge k), returning expected O(log⁡N)O(\log N) search complexity.

HNSW Hierarchical Graph Layer Stepper

Beam Size (efSearch)2 candidates
HNSW Skip-List HierarchyCurrent Level: Layer 2
Layer 2: Express HighwayACTIVE BEAM
Node-ANode-F
Layer 1: Intermediate RoutingPENDING
Node-ANode-CNode-FNode-H
Layer 0: Dense Bottom GraphPENDING
Node-ANode-BNode-CNode-DNode-ENode-FNode-GNode-H
Active LayerLayer 2
Nearest NodeNode-F
Cosine Similarity0.72
Distance Evals8 hops

Index quality and RAM consumption are governed by three coupled parameters. Increasing M (edges per node in upper layers, typically 16–48) raises recall on clustered or high-intrinsic-dimensional manifolds at the expense of graph memory and build cost. Raising efConstruction (beam width during index insertion, typically 64–256) builds cleaner proximity links without adding steady-state query latency, while increasing efSearch dynamically trades query-time CPU distance evaluations for higher recall without rebuilding the index. Using 4-byte node identifiers, HNSW graph link storage per vector sums Layer 0 links (2M⋅4=8M2M \cdot 4 = 8M bytes) plus upper-layer links across expected non-zero layers (∑l=1∞M−l=1M−1\sum_{l=1}^{\infty} M^{-l} = \frac{1}{M-1}):

BytesHNSW/vec≈4dstored+8M+4MM−1+tuple_overhead\text{Bytes}_{\text{HNSW/vec}} \approx 4d_{\text{stored}} + 8M + \frac{4M}{M - 1} + \text{tuple\_overhead}

To shrink 4d4d raw FP32 vector storage so the entire HNSW graph fits inside fast DRAM, indexes apply quantization. Scalar Quantization (SQ8) linearly maps each FP32 coordinate into an 8-bit integer (4x memory reduction, minimal recall loss). Product Quantization (PQ) splits a dd-dimensional vector into mm orthogonal subvectors of dimension d∗=d/md^* = d/m, quantizing each subvector to its nearest centroid among k∗k^* codebook entries (typically k∗=256k^* = 256, costing 1 byte per subspace). Asymmetric Distance Computation (ADC) scores an unquantized query against compressed codes via precomputed m×k∗m \times k^* lookup tables:

d(q,x^)2=∑j=1m∥q(j)−cj(x(j))∥22,ϵPQ≤∑j=1mE ⁣[∥x(j)−cj(x(j))∥22]d(q, \hat{x})^2 = \sum_{j=1}^{m} \left\| q^{(j)} - c_j(x^{(j)}) \right\|_2^2, \quad \epsilon_{\text{PQ}} \le \sum_{j=1}^{m} \mathbb{E}\!\left[\left\|x^{(j)} - c_j(x^{(j)})\right\|_2^2\right]

Product Quantization (IVF-PQ) Subspace Tiler

64× Compression (98.4% RAM saved)
Subspaces (m partitions)m = 8 (d* = 16 dims each)
2 subspaces (Coarse)16 subspaces (Fine)
Codebook Centroids (k*)k* = 256 (8 bits)
16 centroids (4 bits)256 centroids (8 bits/1 byte)
128-Dimensional Vector Partitioned into 8 SubspacesQuantized Centroid Codebook Mapping
Subspace #0c_47[0..15]
Subspace #1c_78[16..31]
Subspace #2c_109[32..47]
Subspace #3c_140[48..63]
Subspace #4c_171[64..79]
Subspace #5c_202[80..95]
Subspace #6c_233[96..111]
Subspace #7c_8[112..127]
FP32 Vector Size512 bytes (128 dims)
Quantized Code Size8 bytes (8 bytes)
Distortion Error ε0.161
Asymmetric DistanceO(m) table lookups

Quantitative Memory & Recall Sizing

Consider indexing N=10,000,000N = 10{,}000{,}000 document chunks of dimension d=1,536d = 1{,}536. Storing raw FP32 vectors requires Mraw=107×1,536×4=61.44 GBM_{\text{raw}} = 10^7 \times 1{,}536 \times 4 = 61.44\text{ GB} before HNSW edges. Adding M = 16 graph links adds roughly 132.3 bytes per node (1.32 GB pure edge arrays, or ~2 GB with database tuple headers), putting total resident memory near 63.5 GB—forcing expensive high-RAM nodes or catastrophic SSD page thrashing. Switching vectors to SQ8 trims vector payload to Msq8=107×1,536×1=15.36 GBM_{\text{sq8}} = 10^7 \times 1{,}536 \times 1 = 15.36\text{ GB} (~17.4 GB total with HNSW links). Compressing further with PQ at m=192m = 192 byte-sized subspaces shrinks vector codes to Mpq=107×192=1.92 GBM_{\text{pq}} = 10^7 \times 192 = 1.92\text{ GB}, fitting easily into memory; pairing fast PQ graph traversal with top-100 exact FP32/FP16 disk rescoring preserves over 97% Recall@10 while cutting DRAM footprint by 16x.

Pre-Filtering, Post-Filtering, and Selectivity Collapse

Production queries rarely search the full index unconstrained; multi-tenant ACLs, document dates, and workspace IDs impose predicates with selectivity s∈(0,1]s \in (0, 1]. Naive post-filtering retrieves k ANN candidates first and discards unauthorized rows afterward—causing empty-result collapse when s=0.02s = 0.02 (10×0.02=0.210 \times 0.02 = 0.2 expected survivors). Naive pre-filtering skips non-matching neighbors mid-traversal, severing bridge paths inside the HNSW graph and stalling before reaching k valid nodes. Modern engines like pgvector solve this with iterative index scans (hnsw.iterative_scan = relaxed_order), expanding the Layer-0 graph search dynamically when predicate selectivity filters out early hops, or falling back to filtered partitioned IVF/bitmap scans when ss drops below 1%.

Trade-offs

Choosing an index architecture trades RAM density, write amplification, filter predictability, and tail latency against target recall.

Index StrategyRecall@10Memory (10M ×\times 1536d)P95 Query LatencyFilter Behavior & Update Cost
Exact Flat Scan100%61.4 GB800–2,400msExact pre-filter, zero index RAM, linear CPU cost
IVF-Flat / IVF-PQ90–96%2.1–16.0 GB (PQ/SQ8)12–35msClean partition pre-filter, degrades on drift without re-clustering
HNSW (FP32 / Halfvec)97–99.5%32.7–63.5 GB3–12msNeeds iterative scan under tight filters, slow index builds
HNSW + PQ + Disk Rescore96–98.5%3.5–5.0 GB RAM + NVMe8–22msBest RAM efficiency, adds one batched NVMe random read per query

Incremental HNSW updates fragment graph connectivity over heavy deletes because tombstoned nodes remain traversal bridges until vacuumed or rebuilt. On write-heavy corpora with high churn, partitioned IVF indexes or segmented LSM vector engines bound memory fragmentation better than monolithic graphs.

Failure modes and misconceptions

Evaluating recall on unfiltered toy datasets masks tenant filter collapse. An HNSW index tuned to 98% Recall@10 across the full corpus can silently drop below 40% recall when a customer's workspace holds only 0.5% of total chunks unless iterative_scan or tenant partitioning is enabled.

Assuming distance scores measure calibrated semantic relevance across models. Cosine similarity of 0.81 from one embedder can correspond to 0.58 from another due to anisotropy and training temperature; changing embedding models without version-stamped reindexing corrupts nearest-neighbor geometry silently.

Ignoring memory bandwidth saturation during HNSW build and page eviction. When HNSW index size exceeds available OS page cache and shared_buffers, random graph hops trigger 4 KB NVMe page faults, spiking P99 query latency from 8ms to over 600ms.

Setting efSearch equal to k during filtered or quantized lookups. Because quantized distances introduce ranking jitter and filters discard hits, set efSearch >= max(64, 4 * k) and rescore the expanded shortlist against full-precision vectors.

Decision scenario

A B2B legal platform serves 12 million clauses across 4,000 customer tenants on PostgreSQL pgvector. Enterprise tenants hold up to 300,000 clauses while new tenants hold under 500, and strict matter-level ACLs apply on every query with a 35ms P95 latency SLO. Keep HNSW inside halfvec(1536) (FP16, cutting raw vector RAM from 73.7 GB to 36.9 GB with negligible recall loss), enable SET LOCAL hnsw.iterative_scan = relaxed_order with ef_search = 100 so rare matters never return zero hits, and route ultra-small tenants (under 2,000 filtered rows estimated by planner stats) to a B-tree metadata lookup plus exact distance sort.

Learning outcomes

  • Derive why L2-normalized Euclidean distance, cosine distance, and inner product share identical nearest-neighbor rankings.
  • Size HNSW graph RAM, quantization compression (SQ8 and PQ), and Layer-0 efSearch beams against recall and P95 latency targets.
  • Prevent pre-filtering graph disconnection and post-filtering empty-result collapse using iterative index scans and planner selectivity thresholds.

Implementation example

This PostgreSQL pgvector schema uses FP16 halfvec HNSW indexing for 2x memory compression alongside iterative filtered scanning and an over-fetched Python query wrapper that rescores top candidates cleanly.

sql
CREATE EXTENSION IF NOT EXISTS vector;
​
CREATE TABLE document_chunks (
id bigserial PRIMARY KEY,
tenant_id uuid NOT NULL,
embedding_version text NOT NULL,
embedding halfvec(1536) NOT NULL,
content text NOT NULL
);
​
CREATE INDEX idx_chunks_tenant ON document_chunks (tenant_id);
CREATE INDEX idx_chunks_hnsw_cos ON document_chunks
USING hnsw (embedding halfvec_cosine_ops)
WITH (m = 16, ef_construction = 128);
python
def search_tenant_chunks(conn, tenant_id: str, query_vec: list[float], top_k: int = 8) -> list[dict]:
with conn.cursor() as cur:
cur.execute("SET LOCAL hnsw.ef_search = 100;")
cur.execute("SET LOCAL hnsw.iterative_scan = relaxed_order;")
cur.execute(
"""
SELECT id, content, 1 - (embedding <=> %s::halfvec) AS cosine_sim
FROM document_chunks
WHERE tenant_id = %s AND embedding_version = 'emb-v3-1536'
ORDER BY embedding <=> %s::halfvec
LIMIT %s;
""",
(query_vec, tenant_id, query_vec, top_k),
)
return [{"id": r[0], "content": r[1], "score": float(r[2])} for r in cur.fetchall()]
Reflect before revealing the guide

Why does increasing HNSW efSearch improve recall on filtered queries without rebuilding the index, and when can it still fail under extreme selectivity?

Prerequisites & Related Concepts (5)

Private notes

0 words
Included In Free Course
Free · Verifiable Credential

FS-102LLM Systems Foundations

Build a connected mental model from tokens through retrieval evaluation security and operations.

24 concepts~18h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next