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
- Explain what an embedding is and why semantic search requires vector similarity, not keyword matching
- Define the k-NN and ANN search problems and state why exact k-NN is impractical at scale
- Describe the HNSW index structure and how it achieves sub-linear search time
- Use pgvector to store embeddings and run similarity queries in PostgreSQL
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.
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.
| Metric | Formula | Range | Use When |
|---|---|---|---|
| Cosine Similarity | cos(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 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:
- Layer 0: the complete graph: every vector is a node with links to its M nearest neighbours
- Higher layers: progressively sparser subgraphs; fewer nodes but long-range "express" connections
- Search: start at the top layer, greedily step toward the query, drop down layers one at a time, and refine in layer 0
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
| System | Type | Index | Highlights |
|---|---|---|---|
| Pinecone | Managed cloud | HNSW + IVF | Serverless; auto-scaling; simple API |
| Weaviate | Open-source / cloud | HNSW | Multi-modal; object storage with vectors |
| Qdrant | Open-source / cloud | HNSW | Written in Rust; payload filtering; on-disk HNSW |
| Milvus | Open-source | IVF, HNSW, SCANN | Kubernetes-native; hybrid scalar+vector search |
| ChromaDB | Open-source (embedded) | HNSW | Python-first; excellent for prototyping |
| pgvector | PostgreSQL extension | IVF, HNSW | Stays 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
6.2 Inserting Embeddings
6.3 Similarity Search Operators
6.4 Creating a Vector Index
6.5 Hybrid Search (Vector + Keyword)
7. ANN Performance Benchmark Intuition
| Algorithm | Recall@10 | Queries/sec (approx.) | Memory |
|---|---|---|---|
| Flat (exact) | 100% | ~10–50 | O(N × d) |
| IVF (nprobe=10) | ~90% | ~500–2000 | O(N × d + centroids) |
| HNSW (ef=64) | ~99% | ~1000–5000 | O(N × d + N × M) |
| HNSW + PQ | ~95% | ~3000–10000 | O(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
- Embeddings map text/images/audio to dense vectors; similarity in vector space records semantic similarity
- Similarity metrics: cosine (text), L2 (images), inner product (recommendations): match the metric to the model
- Exact k-NN is O(N × d) per query: impractical for millions of vectors
- HNSW provides O(log N) approximate search with ~99% recall via a hierarchical graph
- pgvector brings vector search into PostgreSQL: use HNSW index with
vector_cosine_opsfor text embeddings - Hybrid search (vector + BM25 / full-text) often outperforms either alone