Course
AI · Module 04: Embeddings, Chunking & Vector SearchTutorial 12 of 21
AI Course·~1.5 hrs

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!

01 Intuition: Plain-English mental model
02 Visuals: Step-by-step diagrams
03 Practice: Clean examples & tradeoffs

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)). On 10,000 rows, a flat scan in PostgreSQL takes ~4 ms (100% recall!). On 10,000,000 rows, a flat scan reads 60 GB of float32 vectors and takes 8+ seconds per query!
  • Approximate Nearest Neighbor (ANN): Trades 0.5%–2% recall (98%–99.5% accuracy) to drop query latency from 8,000 ms down to 3 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):

HNSW (HIERARCHICAL NAVIGABLE SMALL WORLD) — O(log N) EXPRESS HIGHWAY SEARCHLayer 2 (Express):Long-range jumpsLayer 1 (Arterial):Layer 0 (All Vectors):★ Top-K Found in 3ms!
Figure: Just like a 2D Skip List, HNSW enters at a sparse top layer for giant leaps and zooms into dense local neighbors at Layer 0.

Think of HNSW as a multi-layer 2D Skip List merged with an express flight network:

  1. 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.
  2. Middle Layers (Regional Arterials): Once no closer neighbor exists on Layer L, search drops straight down to Layer L-1 (which has ~m× more nodes) and refines direction.
  3. Layer 0 (Every Vector): Zooms through local neighborhood edges keeping a priority queue of size ef_search to 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% recallSlower 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 & RAMSlower build · Higher RAM (~1.5×–2× vector bytes)Faster build · Lower RAM footprint
Key Tuning Knobsm (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:

Tracing Filtered Vector Search in PostgreSQL pgvector
Interactive LLM Pipeline Tracer · Step 1 of 3 (1. The Classic Pre-0.8 Post-Filtering Trap)
1-- Enable pgvector 0.8+ iterative scan so filtered queries never under-return!
2SET LOCAL hnsw.iterative_scan = 'relaxed_order';
3→SELECT chunk_id, content, 1 - (embedding <=> $1) AS cosine_sim
4→FROM doc_chunks
5→WHERE tenant_id = $2 AND is_archived = FALSE
6→ORDER BY embedding <=> $1 LIMIT 5;
Why Legacy Filtered ANN Returned Fewer Than 5 Rows!CLASSIC RAG BUG
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!
What's Happening: Because HNSW is a global graph, post-filtering a rare tenant could exhaust the 40-candidate buffer before finding 5 tenant matches!

5. Production Code: Complete PostgreSQL pgvector Schema + Python/TS Queries

SQL
-- 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);
SDK:
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)

  1. Operator Mismatch Triggering Silent Seq Scans: Creating your HNSW index with vector_cosine_ops (<=>) and then writing ORDER BY embedding <-> $1 (Euclidean L2 operator!) in SQL cannot use the index — PostgreSQL silently falls back to a full table scan! Always verify with EXPLAIN (ANALYZE, BUFFERS).
  2. Default maintenance_work_mem = 64MB Slowing HNSW Builds 20×: Building an HNSW index on 2 million vectors when maintenance_work_mem is tiny spills graph construction to disk and takes hours instead of 4 minutes! Run SET maintenance_work_mem = '2GB'; in your migration session before CREATE INDEX CONCURRENTLY.
  3. Forgetting ON DELETE CASCADE Between documents and doc_chunks: One of the biggest wins of pgvector over 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

Q1.Why is `HNSW` preferred over `IVFFlat` as the default vector index in production PostgreSQL (`pgvector`)?
Q2.You created `USING hnsw (embedding halfvec_cosine_ops)` on a 5M-row table, yet `EXPLAIN ANALYZE` shows a 4,200ms `Seq Scan`! Which bug is the classic culprit?
Q3.What does switching from `vector(1536)` to `halfvec(1536)` in `pgvector` achieve?
Q4.What problem does `SET LOCAL hnsw.iterative_scan = 'relaxed_order'` solve in `pgvector 0.8+`?

Keep Exploring: Related Lessons & Tools

All Courses →