repobenchmarks // ai vector databases
DATABASES
CREATE EXTENSION vector;

pgvector PostgreSQL Extension

Brings native vector embedding similarity search directly inside standard PostgreSQL with fast HNSW and IVFFlat index algorithms.

Indexes: HNSW & IVFFlat Operators: L2 (`<->`), Cosine (`<=>`), Dot (`<#>`) Stars: >14,000
SELECT title FROM documents ORDER BY embedding <=> $query LIMIT 5; -- Sub-millisecond HNSW

When engineering RAG applications, many teams immediately rush to adopt standalone vector databases like Pinecone, Milvus, or Qdrant. However, managing a dedicated vector database creates data synchronization headaches: when a document is updated in PostgreSQL, you must write two-phase commit logic to update its vector in another database. pgvector turns standard PostgreSQL into a high-performance vector store, allowing you to join vectors directly with relational data in single SQL queries.

HNSW vs IVFFlat Indexing

  • HNSW (Hierarchical Navigable Small World): The gold standard for production vector search. Provides higher recall (accuracy) and faster query execution at the cost of longer build times and higher RAM usage.
  • IVFFlat (Inverted File Flat): Divides vectors into clusters (lists). It builds quickly and consumes less memory, but requires periodic rebuilds as new vectors are inserted to prevent recall degradation.

pgvector Hybrid SQL Query Execution

pgvector Hybrid Relational Filtering Shows PostgreSQL combining relational WHERE filter with vector cosine distance index search in a single scan. Relational Filter WHERE tenant_id = 42 AND is_public = true HNSW Vector Distance Search ORDER BY embedding <=> '[0.12, -0.45, ...]' Executes in a single database transaction

pgvector SQL Quick Reference

-- Enable extension
CREATE EXTENSION IF NOT EXISTS vector;

-- Create table with 1536-dimensional embeddings (OpenAI text-embedding-3-small)
CREATE TABLE documents (
    id SERIAL PRIMARY KEY,
    content TEXT,
    embedding vector(1536)
);

-- Build production HNSW index for cosine distance
CREATE INDEX ON documents USING hnsw (embedding vector_cosine_ops)
WITH (m = 16, ef_construction = 64);

-- Query nearest 5 matches
SELECT content, 1 - (embedding <=> '[0.012, -0.043, ...]') AS similarity
FROM documents
ORDER BY embedding <=> '[0.012, -0.043, ...]'
LIMIT 5;
⚠ Performance Gotcha: `maintenance_work_mem` on Index Build

Building an HNSW index on hundreds of thousands of vectors requires substantial memory. The default PostgreSQL maintenance_work_mem is often set to a meager 64MB, causing index builds to fail or take hours by spilling to disk. Temporarily increase memory in your SQL session before building: SET maintenance_work_mem = '2GB'; to speed up HNSW construction by 10x.

Learn more on the official pgvector GitHub repository.