Simple definition#
A vector database stores embeddings (vectors) together with their text and metadata, and answers one question fast: “which stored vectors are closest to this query vector?” — usually with filters such as “only documents this user may see”.
The problem#
Comparing a query with every vector (exact or brute-force search) is simple and perfectly accurate, but with 10 million 1,024-dimension vectors that is 10 billion multiplications per query. Vector databases use approximate nearest neighbour (ANN) indexes to search a small part of the data and still find almost all of the true nearest neighbours.
The trade-off is measured as recall (what fraction of the true top-k were found) versus latency and memory.
ANN index types#
HNSW — Hierarchical Navigable Small World#
flowchart TB
subgraph L2["Layer 2 — few nodes, long jumps"]
A2((A)) --- D2((D))
end
subgraph L1["Layer 1 — more nodes"]
A1((A)) --- B1((B)) --- D1((D)) --- F1((F))
end
subgraph L0["Layer 0 — all vectors, short links"]
A0((A)) --- B0((B)) --- C0((C)) --- D0((D)) --- E0((E)) --- F0((F)) --- G0((G))
end
D2 -.->|"descend"| D1
D1 -.->|"descend"| D0
Q["Query enters at top,<br/>greedily moves to closer nodes,<br/>drops a layer, repeats"] -.-> A2
- Like a road network: motorways on the top layer, local streets at the bottom.
- Pros: excellent recall and low latency; no training step; supports inserts.
- Cons: memory-hungry (graph + full vectors in RAM); slow to build for huge sets.
- Tuning:
M(links per node),ef_construction(build quality),ef_search(query breadth — higher = better recall, slower). - The default in most vector databases and in pgvector.
IVF — Inverted File index#
Cluster all vectors into, say, 1,000 groups with k-means. At query time, find the nearest few cluster centres (nprobe) and search only inside those clusters.
- Pros: less memory, fast build. Cons: needs training on representative data; recall drops for queries near cluster edges.
PQ — Product Quantization (compression)#
Split each vector into sub-vectors and replace each with the ID of its nearest “code” from a small codebook. A 1,024-float vector (4 KB) can shrink to 64–128 bytes. Often combined as IVF-PQ. Also common: scalar quantization (float32 → int8) and binary quantization (1 bit per dimension) with re-scoring of top candidates using full vectors.
DiskANN and tiered storage#
Graph indexes designed to keep most data on SSD rather than RAM, for billion-scale collections at lower cost.
| Index | Recall | Speed | Memory | Best for |
|---|---|---|---|---|
| Flat (exact) | 100% | Slow at scale | Full vectors | < ~100K vectors, ground truth for testing |
| HNSW | Very high | Very fast | High | Default for most RAG workloads |
| IVF-Flat | High | Fast | Medium | Large, fairly static collections |
| IVF-PQ / quantized | Medium–high | Very fast | Very low | Hundreds of millions to billions |
| DiskANN | High | Fast | Low RAM | Billion-scale on SSD |
Metadata filtering#
Real queries combine similarity with conditions: tenant = 'acme' AND doc_type = 'policy' AND region IN ('EU') AND acl_groups CONTAINS 'hr-staff'.
flowchart LR
subgraph Post["Post-filter"]
P1["ANN top 10"] --> P2["Apply filter"] --> P3["Maybe only 2 left<br/>or zero"]
end
subgraph Pre["Pre-filter / filtered ANN"]
F1["Restrict to matching vectors"] --> F2["ANN within them"] --> F3["Full top 10"]
end
Post-filtering can return too few results when filters are selective. Prefer databases that filter during the ANN search, index the filter fields, and design partitions (for example per tenant) for very selective filters.
Hybrid search#
Vector search understands meaning but can miss exact terms: product codes (“XR-2040”), error numbers, names, acronyms. Keyword search (BM25) is the opposite. Hybrid search runs both and fuses the results, usually with Reciprocal Rank Fusion (RRF). Details in advanced retrieval.
Many stores support both natively: OpenSearch, Elasticsearch, Weaviate, Qdrant, Milvus, Azure AI Search, MongoDB Atlas, and PostgreSQL with pgvector plus full-text search.
Choosing a vector store#
flowchart TD
A{"Already run PostgreSQL<br/>and < ~10–50M vectors?"} -->|"Yes"| PG["pgvector<br/>one database, transactions, SQL filters"]
A -->|"No"| B{"Already run OpenSearch /<br/>Elasticsearch for search?"}
B -->|"Yes"| OS["Use its vector + BM25 hybrid"]
B -->|"No"| C{"Want zero operations?"}
C -->|"Yes"| MAN["Managed: Pinecone, cloud search services,<br/>managed Qdrant/Weaviate/Milvus"]
C -->|"No"| D{"Very large scale or<br/>advanced features?"}
D -->|"Yes"| DED["Dedicated: Milvus, Qdrant, Weaviate"]
D -->|"No"| PG
| Option | Type | Strengths | Watch out for |
|---|---|---|---|
| pgvector (PostgreSQL) | Extension | Reuse existing DB, ACID, joins, SQL filters, backups; HNSW and IVFFlat | Very large scale and high QPS need tuning or sharding |
| OpenSearch / Elasticsearch | Search engine | Mature BM25 + vectors + aggregations; hybrid built in | Cluster operations; JVM tuning |
| Pinecone | Managed SaaS | Serverless, simple, scales | Data leaves your network; cost at scale |
| Milvus / Zilliz | Dedicated, OSS + managed | Billion scale, many index types, GPU | Operational complexity |
| Qdrant | Dedicated, OSS + managed | Fast, strong filtering, quantization | Another system to run |
| Weaviate | Dedicated, OSS + managed | Hybrid search, modules, multi-tenancy | Another system to run |
| Redis, MongoDB Atlas, Oracle, Cassandra, Neo4j | Multi-model DBs | Reuse what you have | Feature depth varies |
| Cloud services | Azure AI Search, Vertex AI Vector Search, Bedrock Knowledge Bases | Integrated with cloud AI stacks | Cloud lock-in |
Scaling and operations#
- Memory sizing (HNSW): roughly vectors × dimensions × 4 bytes × ~1.5 for graph overhead. 10M × 1,024 dims ≈ 40 GB of vectors → ~60 GB RAM. Quantization cuts this 4–32×.
- Sharding spreads vectors over nodes; replicas add query throughput and availability.
- Multi-tenancy: a tenant ID filter (simple), a partition/namespace per tenant (better isolation and performance), or an index per tenant (strongest isolation, more overhead).
- Updates and deletes: HNSW deletes are often “soft” and need periodic compaction/re-indexing.
- Backups and re-indexing: treat the index as derived data — keep sources and the pipeline so you can rebuild it.
Common mistakes#
Review questions#
What is a vector database and why not just use a normal database? A store optimised for nearest-neighbour search over high-dimensional vectors, with metadata filtering. Relational indexes (B-trees) cannot answer “closest vectors” efficiently; vector databases use ANN indexes such as HNSW. Many normal databases now add vector indexes (pgvector), which is often enough.
Explain HNSW. A multi-layer proximity graph. Upper layers have few nodes and long links; the bottom layer has all vectors with short links. Search starts at the top, greedily moves toward the query, descends layer by layer, and finishes with a local search at the bottom. It gives high recall at low latency but uses a lot of memory.
HNSW vs IVF? HNSW: better recall/latency, more memory, no training, supports incremental inserts. IVF: clusters vectors and searches a few clusters; less memory and faster to build, needs training and can lose recall at cluster boundaries. IVF-PQ adds compression for very large scale.
How do you implement multi-tenancy in a vector store? Filter by tenant ID on every query (simplest), partition or namespace per tenant (better isolation and filter performance), or separate indexes per tenant (strongest isolation). Choose by isolation requirements, tenant count and size skew.
How would you choose a vector database for an enterprise? Start with what you run: pgvector for PostgreSQL shops at moderate scale, OpenSearch/Elasticsearch if you have search clusters and need hybrid search. Consider managed or dedicated stores for very large scale, high QPS or zero-ops requirements. Validate with recall, latency, filter performance, security features and cost.
Summary#
- Vector databases answer “nearest vectors with filters” using ANN indexes.
- HNSW is the default: high recall, low latency, memory-heavy. IVF and PQ trade recall for scale and memory.
- Filter during search, index the filter fields, and enforce ACLs in the query.
- Hybrid (vector + BM25) beats either alone for enterprise text.
- Start with pgvector or your existing search engine; move when measurements demand it.
References#
- Malkov & Yashunin, Efficient and robust approximate nearest neighbor search using Hierarchical Navigable Small World graphs, 2016.
- Jégou, Douze, Schmid, Product Quantization for Nearest Neighbor Search, 2011.
- pgvector documentation.