4.3 Vector Indexes (HNSW vs IVFFlat) & PostgreSQL pgvector
Understand how Approximate Nearest Neighbor (ANN) indexes search 10 million vectors in 3 milliseconds: compare HNSW vs IVFFlat, tune pgvector in PostgreSQL, and avoid the classic Filtered-ANN zero-results trap!
1. Why B+ Trees Fail on 1,536-Dimensional Vectors
In our SQL course, we saw that B+ Tree indexes find exact keys in O(log N) because 1D numbers and strings have a total ordering (10 < 42 < 99). In 1,536-dimensional vector space, there is no left-to-right sort order — and because of the Curse of Dimensionality, classical spatial trees (k-d trees, R-trees) degrade to scanning 100% of the table once dimensions pass ~20!
- Exact
k-NN(Flat Scan): Computes dot product against every single row (O(N × d)). On10,000rows, a flat scan in PostgreSQL takes~4 ms(100%recall!). On10,000,000rows, a flat scan reads60 GBof float32 vectors and takes8+ secondsper query! - Approximate Nearest Neighbor (
ANN): Trades0.5%–2%recall (98%–99.5%accuracy) to drop query latency from8,000 msdown to3 ms!
2. How HNSW Searches Millions of Vectors in O(log N)
Today's dominant ANN index — used inside pgvector, Qdrant, Pinecone, Weaviate, Milvus, and OpenSearch — is HNSW (Hierarchical Navigable Small World):
Think of HNSW as a multi-layer 2D Skip List merged with an express flight network:
- Top Layer (Sparse Express Highway): Contains only a handful of hub nodes connected by long-range edges across the vector space. Search starts here and takes giant greedy hops toward the query vector.
- Middle Layers (Regional Arterials): Once no closer neighbor exists on Layer
L, search drops straight down to LayerL-1(which has ~m× more nodes) and refines direction. - Layer 0 (Every Vector): Zooms through local neighborhood edges keeping a priority queue of size
ef_searchto return the Top-K nearest vectors in milliseconds!
HNSW vs. IVFFlat Comparison
| Feature | **HNSW (Default Choice!) ** | **IVFFlat (Inverted File + k-Means Centroids) ** |
|---|---|---|
| Query Speed & Recall | 🏆 Fastest (2–5 ms) at 99% recall | Slower at equivalent high recall |
| Empty-Table Safe? | ✅ Yes! Can create index on an empty table; handles live inserts/updates cleanly | ❌ No! Must run after data exists so k-Means centroids train accurately; drifts as data shifts! |
| Index Build Time & RAM | Slower build · Higher RAM (~1.5×–2× vector bytes) | Faster build · Lower RAM footprint |
| Key Tuning Knobs | m (edges/node, default 16), ef_construction (64), ef_search (40–100) | lists (sqrt(N) clusters), probes (clusters checked per query) |
3. Why PostgreSQL + pgvector Should Be Your Default Architecture
Beginners often spin up a separate cloud Vector Database on day one — and immediately hit a nightmare of dual-write sync bugs (document deleted in Postgres, stale zombie vector still lives in external Vector DB!), separate ACL permissions, and extra network hops.
With pgvector (0.7+ / 0.8+), your vectors live inside the exact same ACID transaction, foreign keys, Row-Level Security, and JOINs as your users, tenants, and documents — effortlessly scaling to 5M–50M+ vectors on a single well-sized instance!
Cut pgvector RAM in Half with halfvec (float16 Quantization!)
A vector(1536) column stores 32-bit floats (1536 × 4 = 6 KB per chunk). Switching to halfvec(1536) (16-bit floats introduced in pgvector 0.7) cuts index RAM and disk size by 50% (3 KB per chunk) with virtually zero recall loss (< 0.2%) — and supports dimensions up to 4,000!
4. Wire-Level Trace: Avoiding the Classic "Filtered HNSW Zero-Results Trap"
What happens when you combine WHERE tenant_id = 'acme' (matching only 0.1% of rows) with an HNSW index? Click Next to see the #1 production pgvector bug — and how hnsw.iterative_scan (pgvector 0.8+) + Partial/Partitioned Indexes fix it:
HNSW fetched top ef_search=40 global neighbors across ALL tenants -> PostgreSQL filtered WHERE tenant_id = 'acme' -> Only 1 of those 40 belonged to 'acme' -> Returned 1 row instead of 5!
5. Production Code: Complete PostgreSQL pgvector Schema + Python/TS Queries
-- 1. Enable extension & create production chunks table with halfvec(768)
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE doc_chunks (
chunk_id TEXT PRIMARY KEY,
tenant_id UUID NOT NULL,
doc_id UUID NOT NULL REFERENCES documents(id) ON DELETE CASCADE,
breadcrumb TEXT NOT NULL,
content TEXT NOT NULL,
embedding halfvec(768) NOT NULL,
tsv tsvector GENERATED ALWAYS AS (to_tsvector('english', breadcrumb || ' ' || content)) STORED
);
-- 2. HNSW Vector Index + GIN Full-Text Index (Ready for Hybrid Search in Module 05!)
CREATE INDEX CONCURRENTLY idx_chunks_embedding_hnsw
ON doc_chunks USING hnsw (embedding halfvec_cosine_ops)
WITH (m = 16, ef_construction = 64);
CREATE INDEX CONCURRENTLY idx_chunks_tsv_gin ON doc_chunks USING gin (tsv);
CREATE INDEX CONCURRENTLY idx_chunks_tenant ON doc_chunks (tenant_id);
import psycopg
from pgvector.psycopg import register_vector
def search_tenant_chunks(conn_str: str, tenant_id: str, query_vec: list[float], k: int = 5):
with psycopg.connect(conn_str) as conn:
register_vector(conn)
with conn.cursor() as cur:
cur.execute("SET LOCAL hnsw.ef_search = 80;")
cur.execute("SET LOCAL hnsw.iterative_scan = 'relaxed_order';")
cur.execute(
"""
SELECT chunk_id, breadcrumb, content,
1 - (embedding <=> %s::halfvec) AS cosine_similarity
FROM doc_chunks
WHERE tenant_id = %s
ORDER BY embedding <=> %s::halfvec
LIMIT %s;
""",
(query_vec, tenant_id, query_vec, k),
)
return cur.fetchall()6. What Breaks in Production (War Stories)
- Operator Mismatch Triggering Silent
Seq Scans: Creating your HNSW index withvector_cosine_ops(<=>) and then writingORDER BY embedding <-> $1(EuclideanL2operator!) in SQL cannot use the index — PostgreSQL silently falls back to a full table scan! Always verify withEXPLAIN (ANALYZE, BUFFERS). - Default
maintenance_work_mem = 64MBSlowing HNSW Builds 20×: Building an HNSW index on 2 million vectors whenmaintenance_work_memis tiny spills graph construction to disk and takes hours instead of 4 minutes! RunSET maintenance_work_mem = '2GB';in your migration session beforeCREATE INDEX CONCURRENTLY. - Forgetting
ON DELETE CASCADEBetweendocumentsanddoc_chunks: One of the biggest wins ofpgvectorover external vector DBs is transactional cleanup — deleting a document row cascades and purges all 80 of its vector chunks atomically with zero stale data leaks!
Module 4.3 Mastery Check — HNSW, IVFFlat & pgvector
Keep Exploring: Related Lessons & Tools
All Courses →Compare two versions of text, source code, config files, or JSON payloads side-by-side using exact LCS diffing with recursive JSON key sorting and patch export.
Paste LeetCode-style level-order tree arrays, graph edge lists, or 2D matrices to render clean vector SVG diagrams and DFS traversals.