Quick reference

Vector Databases & Retrieval Architecture Cheat Sheet: Concepts, Indexing, Quantization & Selection

A high-density reference guide to vector databases and semantic retrieval: covering distance metric formulas, ANN index algorithms (HNSW, IVF, DiskANN, ScaNN), quantization memory sizing, inline filtering, RRF hybrid search, and tiered comparison of native vector DBs, database extensions, and managed cloud services.

· Published

A Vector Database stores high-dimensional dense and sparse embeddings alongside metadata, enabling millisecond-scale Approximate Nearest Neighbor (ANN) similarity search as the core retrieval and memory layer for RAG, semantic search, and AI agents.

Workload / Constraint Recommended Category Representative Solutions Why It Fits
Existing PostgreSQL stack, under ~10M vectors Relational DB Extension pgvector (+ halfvec / HNSW) Reuses ACID transactions, SQL JOINs, and existing ops with zero new infrastructure
Full-text BM25 + vector hybrid scoring Search Engine Extension Elasticsearch / OpenSearch / Vespa Mature inverted index + multi-stage hybrid ranking ecosystem
Standalone high-QPS service with heavy filtering Dedicated Distributed Vector DB Qdrant / Milvus / Weaviate Purpose-built storage engine, payload pre/inline filtering, horizontal scaling
Local dev, edge/desktop apps, or data lake direct reads Embedded / Columnar Vector DB LanceDB / Chroma / FAISS In-process execution with zero-copy Apache Arrow / Parquet integration
Massive cold/warm datasets at minimal storage cost Object-Storage Native SaaS Turbopuffer Stores truth in object storage (S3/GCS) + local NVMe/RAM hot cache
Zero-ops serverless deeply tied to cloud ecosystems Fully Managed Cloud Service Pinecone / Vertex AI Vector Search / Azure AI Search Elastic serverless scaling with native cloud IAM and monitoring

🔗 Related Cheat Sheets: LLM & AI Agent Concepts · Core AI Algorithms · PostgreSQL Commands · Redis Commands · MongoDB Commands


1. Core Concepts & Distance Metrics

1.1 Essential Terminology

Term Definition Engineering Considerations
Embedding Fixed-length float array encoding semantic meaning of text, images, or audio Common dimensions: 384 / 768 / 1024 / 1536 / 3072; RAM and compute scale linearly with dimension
ANN (Approximate Nearest Neighbor) Index-accelerated search trading tiny recall (e.g., 95%–99%) for 100×–1000× speedup Core latency vs. recall tradeoff, contrasted with brute-force exact k-NN scan
Metadata Filtering Constraining vector search by scalar attributes (tenant, timestamp, ACL, category) Distinguish Pre-filtering, Single-stage / Inline, and Post-filtering
Hybrid Search Combining dense vectors (semantics) with sparse vectors / BM25 (exact lexical match) Fixes pure semantic search misses on SKUs, error codes, acronyms, and proper nouns
Sparse Vector High-dimensional vector where most entries are 0 (e.g., SPLADE, BM25 term weights) Stores only non-zero indices and weights; pairs naturally with dense retrieval

1.2 Three Core Distance & Similarity Metrics

Cosine(u, v) = (u · v) / (‖u‖₂ · ‖v‖₂)
IP(u, v)     = u · v = ∑ᵢ (uᵢ × vᵢ)
L₂(u, v)     = √( ∑ᵢ (uᵢ − vᵢ)² )
Metric Meaning Mathematical Equivalence Typical Use Cases
Cosine Similarity Measures angle only, ignoring magnitude (−1 to 1; distance = 1 - cos) Identical ranking to Inner Product when vectors are L₂-normalized Text semantic search, RAG, sentence embeddings (default choice)
Inner Product (IP / Dot) Reflects both angle and vector magnitude; lowest compute cost Replace Cosine with IP on unit-normalized vectors to skip norms Two-tower recommender systems, normalized embeddings (e.g., OpenAI)
Euclidean Distance (L₂) Straight-line geometric distance; smaller means closer For unit vectors: L₂² = 2 − 2 · cos(u, v) Image/face embeddings, spatial clustering, magnitude-sensitive features

2. ANN Index Algorithms & Vector Quantization

2.1 Vector Index Comparison

Index Type Mechanism RAM Usage Latency & Recall Scale & Representative Engines
Flat (Exact Scan) Exhaustive distance computation across all vectors Moderate (raw/quantized vectors only) 100% recall; latency degrades sharply past ~100K rows Small datasets (<100K) and ground-truth recall benchmarks
IVF-Flat (Inverted File) K-Means clustering into nlist buckets; scans nearest nprobe buckets Low (minimal structural overhead) Tunable via nprobe; moderate-to-high recall 1M–10M rows under tight memory budgets (FAISS / Milvus / pgvector)
IVF-PQ (IVF + Product Quantization) Bucket partitioning plus sub-vector codebook compression Very Low (16×–64× smaller) Ultra-fast; single-pass recall drops, usually paired with rescoring 100M+ in-memory search (FAISS / Milvus / LanceDB)
HNSW (Hierarchical Navigable Small World) Multi-layer skip-list proximity graph (coarse top layers, fine bottom layer) High (vectors + graph edges in RAM or hot mmap) Millisecond latency + 95%–99% recall; industry default 1M–100M+ real-time low-latency search (Qdrant / Milvus / Weaviate / pgvector)
DiskANN (Vamana Graph) SSD-optimized graph: compressed vectors in RAM, full graph/vectors on NVMe Low (5×–10× RAM reduction) Single-node 100M+ vectors at ms latency; relies on fast NVMe IOPS Memory-constrained 100M–1B+ datasets (Milvus / LanceDB / Azure)
ScaNN Anisotropic Vector Quantization + tree partitioning Low–Moderate Top recall-per-latency curve under Inner Product Large-scale recommendation & search (Vertex AI Vector Search / OSS)

HNSW Core Tuning Parameters:

  • M (max bidirectional links per node, typically 16–64): Higher M improves recall on high-dimensional data at the cost of RAM and build time.
  • efConstruction (candidate list size during index build, typically 100–400): Affects build time only; higher values yield higher-quality graphs.
  • efSearch (dynamic search beam width at query time, must be ≥ top_k): Only parameter tunable per query; increasing raises recall and lowers QPS.

2.2 Quantization & Memory Sizing

Reference baseline for 10 million × 1536-dimensional vectors (raw FP32):

Raw Vector Size ≈ N × D × 4 Bytes   (HNSW graph adjacency adds ~1.2×–1.5× overhead)
Quantization Width / Dim Compression 10M × 1536-dim Size Accuracy Tradeoff & Usage
FP32 (Uncompressed) 32-bit (4 B) 1× ~57.2 GB Baseline precision; expensive to keep resident in RAM
FP16 / BF16 (Half Precision) 16-bit (2 B) 2× ~28.6 GB Virtually lossless recall (e.g., pgvector halfvec); high ROI
SQ8 (Scalar Quantization Int8) 8-bit (1 B) 4× ~14.3 GB Typically preserves 97%+ recall; standard production default
PQ (Product Quantization) Subspace/codebook 16×–64× ~1–4 GB Requires codebook training; pair with oversampling + rescore
BQ (Binary Quantization 1-bit) 1-bit 32× ~1.79 GB Ultra-fast Hamming scan; pair with 3×–5× rescore (best for ≥1024-dim)

3. Tiered Comparison of Vector Databases & Search Engines

3.1 Dedicated Native Vector Databases

Product License / Deployment Language & Storage Engine Indexing & Key Capabilities Best Fit
Qdrant Apache 2.0 / Self-hosted & Cloud Rust; in-memory, mmap disk & on-disk quantization HNSW + SQ8/BQ; native sparse vectors and fast payload filter indexing High-QPS standalone vector service, multi-tenancy, complex filters
Milvus Apache 2.0 / Distributed & Zilliz Cloud Go control plane + C++ execution; disaggregated object storage + MQ IVF, HNSW, DiskANN, GPU CAGRA; multi-tenant partitions Billion-scale, high-throughput enterprise platforms
Weaviate BSD-3-Clause (select enterprise add-ons closed) Go; built-in object storage + inverted index HNSW + dynamic/PQ/BQ quantization; GraphQL/REST, built-in vectorizer modules RAG apps needing integrated embedding pipelines
Chroma Apache 2.0 / Embedded & Client-Server Python / Rust core; SQLite + local or distributed store HNSW; minimal API with tight LangChain / LlamaIndex integration Rapid AI prototyping and small-to-medium Python RAG
LanceDB Apache 2.0 / Embedded & Enterprise Rust; built on Lance columnar format & Apache Arrow IVF-PQ, HNSW, DiskANN; zero-copy I/O, native multimodal (video/audio/tables) Embedded local apps, serverless object-storage reads, multimodal lakes
Pinecone Proprietary Serverless SaaS Managed distributed engine (evolved from Pods to Serverless) Disaggregated proprietary index; sparse-dense hybrid, namespace isolation Zero-ops cloud teams prioritizing managed simplicity
Turbopuffer Proprietary SaaS / BYOC Rust; object storage (S3/GCS) as source of truth + NVMe/RAM cache Centroid-based index (SPFresh-style) avoiding random-I/O graph hops; full-text + vector Massive cold/warm datasets (e.g., code indexing) at ultra-low storage cost

3.2 Vector Search Libraries (Not Full Databases)

Product License Scope & Boundaries Typical Use Cases
FAISS (Meta) MIT C++ / Python similarity search library (no metadata persistence, distributed transactions, or auth server); CPU SIMD & multi-GPU Flat/IVF/HNSW Offline batch similarity, ML research, embedded kernel inside custom engines

3.3 Traditional Databases & Search Engine Extensions

Product Foundation Vector Indexing & Capabilities Strengths & Limitations
pgvector PostgreSQL extension (incl. Supabase ecosystem) vector / halfvec / sparsevec / bit types; HNSW & IVFFlat Pros: ACID transactions, SQL JOINs, zero new ops; Cons: write amplification & RAM pressure past ~10M–50M rows
Elasticsearch / OpenSearch Lucene inverted index + HNSW Native Dense Vector + BM25 hybrid search, RRF fusion, nested filtering Pros: Reuses existing search team stack; Cons: heavy JVM off-heap RAM and segment merge overhead
Redis (Query Engine) In-memory KV store Flat & HNSW indexes, sub-millisecond RAM latency, real-time streaming Pros: Ultra-low latency for semantic caching & feature stores; Cons: high RAM cost at scale
MongoDB Atlas Search Document DB (Atlas managed / Local CLI) Lucene-based HNSW index alongside BSON business documents Pros: Eliminates dual-write sync between doc & vector DBs; Cons: core search tied to Atlas
SingleStore Distributed HTAP SQL DB SQL + native vector functions (dot product / L₂), columnstore + rowstore Enterprise workloads mixing real-time SQL analytics and transactions
Vespa Apache 2.0 big-data serving engine HNSW + exact/approximate hybrid, multi-phase ML ranking (Tensor/XGBoost/ONNX) Large-scale search & recommendation platforms; steeper ops/learning curve

3.4 Fully Managed Cloud Services

Service Cloud Provider Core Architecture & Highlights
Vertex AI Vector Search (formerly Matching Engine) Google Cloud (GCP) Powered by Google ScaNN; supports billion-scale streaming updates and sparse-dense hybrid search
Amazon OpenSearch Serverless / Aurora pgvector AWS Managed serverless search clusters and RDS/Aurora vector extensions; native Amazon Bedrock integration
Azure AI Search Microsoft Azure Built-in Semantic Ranker, integrated vectorization pipelines, and enterprise RBAC document security

4.1 Metadata Filtering Execution Modes

Strategy Execution Order Failure Mode & Mitigation
Pre-filtering Evaluate scalar index to produce an ID bitmap, then run vector search Under selective filters (<1% match), pure graph traversal disconnects; Mitigation: auto-fallback to exact scan
Post-filtering Retrieve global vector Top-K, then drop items failing scalar predicates Returns fewer than K results (or empty) on selective filters; Mitigation: never use alone without heavy oversampling
Single-stage / Inline Check the scalar filter bitmap dynamically during each HNSW graph hop Modern default (Qdrant / Milvus / Weaviate / pgvector 0.8+ iterative scan), balancing recall and latency

4.2 Reciprocal Rank Fusion (RRF)

When merging dense semantic retrieval and BM25 lexical retrieval, score scales differ across engines; RRF combines rankings directly without score calibration:

RRF_Score(d) = ∑_{r ∈ R} 1 / (k + rank_r(d))     (standard smoothing constant k = 60)

5. Production Snippets

5.1 pgvector Schema, HNSW Index & Iterative Scan (SQL)

-- 1. Enable extension and create table with half-precision vectors + full-text column
CREATE EXTENSION IF NOT EXISTS vector;

CREATE TABLE documents (
    id BIGSERIAL PRIMARY KEY,
    tenant_id INT NOT NULL,
    content TEXT NOT NULL,
    embedding halfvec(1536),          -- float16 saves 50% memory vs float32
    fts tsvector GENERATED ALWAYS AS (to_tsvector('simple', content)) STORED
);

-- 2. Build Cosine HNSW index (M=16, ef_construction=128) and GIN full-text index
CREATE INDEX idx_docs_emb_hnsw ON documents
    USING hnsw (embedding halfvec_cosine_ops)
    WITH (m = 16, ef_construction = 128);

CREATE INDEX idx_docs_fts ON documents USING gin (fts);

-- 3. Tune ef_search and enable iterative scan (pgvector 0.8+) for filtered queries
SET hnsw.ef_search = 100;
SET hnsw.iterative_scan = relaxed_order;

SELECT id, content, 1 - (embedding <=> $1::halfvec) AS cosine_sim
FROM documents
WHERE tenant_id = 42
ORDER BY embedding <=> $1::halfvec
LIMIT 10;

pgvector Distance Operators: <-> Euclidean (L₂) · <=> Cosine distance (1 - cos) · <#> Negative Inner Product · <+> Manhattan (L₁).

5.2 Qdrant Collection, Binary Quantization & Payload Filtering (Python)

from qdrant_client import QdrantClient, models

client = QdrantClient(url="http://localhost:6333")

# Create collection with on-disk vectors and in-RAM binary quantization
client.create_collection(
    collection_name="knowledge_base",
    vectors_config=models.VectorParams(
        size=1536,
        distance=models.Distance.COSINE,
        on_disk=True,
    ),
    quantization_config=models.BinaryQuantization(
        binary=models.BinaryQuantizationConfig(always_ram=True)
    ),
)

# Index frequently filtered metadata fields for fast inline filtering
client.create_payload_index(
    collection_name="knowledge_base",
    field_name="tenant_id",
    field_schema=models.PayloadSchemaType.KEYWORD,
)

# Query with metadata filter + oversampled rescoring
hits = client.query_points(
    collection_name="knowledge_base",
    query=[0.012, -0.045, ...],  # 1536-dim query vector
    query_filter=models.Filter(
        must=[models.FieldCondition(key="tenant_id", match=models.MatchValue(value="org_a"))]
    ),
    search_params=models.SearchParams(
        quantization=models.QuantizationSearchParams(rescore=True, oversampling=3.0)
    ),
    limit=10,
).points

Related topics