IIT Madras Zanzibar · Teaching

Module 10: Modern & AI Data Systems · Lecture 43 · Week 15

Vector Databases & Embeddings

Storing high-dimensional embeddings, approximate nearest neighbour search, and pgvector

Learning Objectives

1. What Is an Embedding?

Machine learning models (language models, image encoders, and audio models) map complex inputs (text, images, audio) into a fixed-size vector of floating-point numbers. This vector is called an embedding. Semantically similar inputs map to vectors that are close together in the embedding space.

Text → Embedding model → Dense vector "mango ripeness detection" → [0.12, -0.34, 0.85, ..., 0.07] (1536 dimensions) "fruit maturity assessment" → [0.11, -0.31, 0.82, ..., 0.09] ← close! "database transaction log" → [-0.72, 0.14, -0.03, ..., 0.55] ← far away Popular embedding models: OpenAI text-embedding-3-small → 1536 dimensions sentence-transformers all-MiniLM → 384 dimensions Google Gemini embeddings → 768 dimensions
768
BERT embedding dims
1,536
OpenAI ADA-002 dims
3,072
OpenAI text-3-large dims

2. Similarity Metrics

Two vectors can be compared using different distance functions. The choice depends on the embedding model: the model is trained to use a specific metric, so you must match it.

MetricFormulaRangeUse When
Cosine Similaritycos(u,v) = (u·v) / (|u||v|)[−1, 1]Text, normalized embeddings: measures angle, not magnitude
Euclidean Distance (L2)d = √(Σ(uᵢ−vᵢ)²)[0, ∞)Image features, unnormalized vectors
Inner Product (dot product)u·v = Σ uᵢvᵢ(−∞, ∞)Recommendation systems (ALS-trained embeddings)
Manhattan Distance (L1)d = Σ|uᵢ−vᵢ|[0, ∞)Sparse vectors, reliable to outliers

Cosine Similarity = L2 Distance on Unit Vectors

If all embedding vectors are L2-normalized (length = 1), then cosine similarity and dot product are identical, and maximizing cosine similarity is equivalent to minimizing Euclidean distance. Most modern text embedding models return unit-normalized vectors. Verify this for your model before choosing a metric.

3. The k-Nearest Neighbour Problem

Given a query vector q and a database of N vectors, find the k vectors most similar to q. This is the k-Nearest Neighbour (k-NN) problem.

Exact k-NN cost: Compare q against every vector in the database: O(N × d) where N = number of vectors, d = dimensionality Example: N = 10 million, d = 1536 10,000,000 × 1536 = 15 billion multiplications per query At 10 GFLOP/s → ~1.5 seconds per query: too slow for real-time

Exact k-NN is impractical for large collections. Instead, Approximate Nearest Neighbour (ANN) algorithms sacrifice a small amount of recall for much faster search.

4. ANN Algorithms

4.1 Flat Index (Brute-Force Baseline)

Compare the query against every vector. Exact results. Used as the baseline for measuring recall. FAISS library implements this as the IndexFlatL2 index. Feasible only up to ~100K vectors on CPU.

4.2 Inverted File Index (IVF)

Cluster the vectors (e.g., via k-means) into C centroids. At query time, search only the nearest nprobe clusters. Reduces search space from N to roughly N/C × nprobe. Trade-off: increasing nprobe improves recall but increases latency.

4.3 HNSW: Hierarchical Navigable Small World

HNSW is the most widely used ANN algorithm. It builds a multi-layer graph where each node is a vector:

HNSW parameters: M = number of connections per node (typical: 16–64) efConstruction = candidate queue size during index build (higher → better quality, slower build) ef = candidate queue size during search (higher → better recall, slower query) Search complexity: O(log N) in practice (empirically sub-linear) Memory: O(N × M × d_pointer) for the graph + O(N × d × 4 bytes) for vectors Example: 10M vectors, d=1536, M=32, fp32 Graph memory: 10M × 32 × 4 bytes ≈ 1.3 GB Vector memory: 10M × 1536 × 4 bytes ≈ 61 GB (use fp16 or quantization to halve)

4.4 Product Quantization (PQ): Compression

Vectors are split into M sub-vectors; each sub-vector is quantized to one of K codewords. Instead of storing 1536 float32 values (6 KB), store M indices (e.g., 8 bytes for M=8, K=256). Enables storing billions of vectors in memory at the cost of approximate distance computation.

5. Dedicated Vector Database Systems

SystemTypeIndexHighlights
PineconeManaged cloudHNSW + IVFServerless; auto-scaling; simple API
WeaviateOpen-source / cloudHNSWMulti-modal; object storage with vectors
QdrantOpen-source / cloudHNSWWritten in Rust; payload filtering; on-disk HNSW
MilvusOpen-sourceIVF, HNSW, SCANNKubernetes-native; hybrid scalar+vector search
ChromaDBOpen-source (embedded)HNSWPython-first; excellent for prototyping
pgvectorPostgreSQL extensionIVF, HNSWStays in your existing Postgres; full ACID

6. pgvector: Vector Search in PostgreSQL

pgvector is a PostgreSQL extension that adds a vector data type, vector indexes (IVF and HNSW), and distance operators. It lets you add semantic search to an existing Postgres database without a separate vector store.

6.1 Setup and Schema

-- Enable the extension (one-time) CREATE EXTENSION IF NOT EXISTS vector; -- Store documents with their embeddings CREATE TABLE articles ( id SERIAL PRIMARY KEY, title TEXT, content TEXT, embedding vector(1536) -- 1536-dimensional vector (OpenAI text-embedding-3-small) );

6.2 Inserting Embeddings

-- Insert a row with its embedding (Python → SQL via psycopg2) INSERT INTO articles (title, content, embedding) VALUES ( 'Mango Ripeness Detection', 'We present a CNN-based approach...', '[0.12, -0.34, 0.85, ..., 0.07]'::vector -- 1536 floats );

6.3 Similarity Search Operators

-- Cosine distance: <=> (lower is more similar) SELECT title, 1 - (embedding <=> '[...]'::vector) AS cosine_similarity FROM articles ORDER BY embedding <=> '[...]'::vector LIMIT 5; -- L2 distance: <-> SELECT title FROM articles ORDER BY embedding <-> '[...]'::vector LIMIT 5; -- Inner product: <#> (negated, lower = higher similarity) SELECT title FROM articles ORDER BY embedding <#> '[...]'::vector LIMIT 5;

6.4 Creating a Vector Index

-- HNSW index (recommended for most workloads) CREATE INDEX ON articles USING hnsw (embedding vector_cosine_ops) WITH (m = 16, ef_construction = 64); -- IVF Flat index (lower memory, good for batch search) CREATE INDEX ON articles USING ivfflat (embedding vector_l2_ops) WITH (lists = 100); -- sqrt(N) lists is a common heuristic -- After bulk load, run ANALYZE so the planner knows the index exists ANALYZE articles;

6.5 Hybrid Search (Vector + Keyword)

-- Combine full-text search with vector similarity SELECT a.title, ts_rank(to_tsvector(a.content), plainto_tsquery('mango ripeness')) AS text_score, 1 - (a.embedding <=> '[...]'::vector) AS vector_score FROM articles a WHERE to_tsvector(a.content) @@ plainto_tsquery('mango ripeness') ORDER BY vector_score DESC LIMIT 10;

7. ANN Performance Benchmark Intuition

AlgorithmRecall@10Queries/sec (approx.)Memory
Flat (exact)100%~10–50O(N × d)
IVF (nprobe=10)~90%~500–2000O(N × d + centroids)
HNSW (ef=64)~99%~1000–5000O(N × d + N × M)
HNSW + PQ~95%~3000–10000O(N × M/8): compact footprint

The Recall-Latency Trade-Off

ANN indexes offer a configurable trade-off: increasing ef (HNSW) or nprobe (IVF) improves recall (more true nearest neighbours found) but increases query latency. For a recommendation system, 95% recall at 1 ms is better than 99.9% recall at 100 ms. Always benchmark against your actual use-case query patterns and recall requirements.

8. Summary