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 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;
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.
Discussion & Issues
Comments
Post a Comment