pgvector is the PostgreSQL extension that adds a vector type and approximate-nearest-neighbour indexes so you can do similarity search alongside your relational data. This is now the default storage layer for RAG pipelines and semantic search inside web applications — no separate vector DB. This article covers the install, the index choice (HNSW vs IVFFlat), the dimension and distance trade-offs, and the operational sizing we use on engagements running a few million to a few hundred million vectors.
How to verify
Confirm pgvector is available and inspect the indexes on your vector column:
psql -d app -c "SELECT * FROM pg_available_extensions WHERE name = 'vector';"
psql -d app -c "CREATE EXTENSION IF NOT EXISTS vector;"
psql -d app -c "\d documents"
psql -d app -c "SELECT indexname, indexdef FROM pg_indexes
WHERE tablename = 'documents';"
psql -d app -c "EXPLAIN (ANALYZE, BUFFERS)
SELECT id FROM documents
ORDER BY embedding <=> '[0.1, 0.2, ...]' LIMIT 10;"
If the EXPLAIN shows Index Scan using ... hnsw (or ivfflat), the ANN index is being used.
What’s happening
pgvector stores vectors as a sequence of single-precision floats and supports three distance operators: <-> (L2), <=> (cosine), and <#> (negative inner product). An exact nearest-neighbour search sorts every row by distance — fine for tens of thousands of rows, but the latency curves go vertical past a million. ANN indexes trade exact correctness for speed.
HNSW (Hierarchical Navigable Small World) builds a multi-layer graph where each layer connects vectors that are close in space. Search is a greedy walk down from the top layer. Pros: high recall, fast queries, no training step. Cons: builds are slow, memory-hungry, parameters tuned at index creation.
IVFFlat partitions vectors into Voronoi cells around centroids found by k-means clustering. Search probes a configurable number of cells. Pros: smaller index, faster build, recall scales with probe count. Cons: needs representative training data, recall drops if your distribution shifts.
For most engagements we run, HNSW is the default — recall and latency win for read-heavy semantic search. IVFFlat shines when the dataset is huge and updates are batched.
The procedure
-
Pick the dimension and stick to it. OpenAI’s
text-embedding-3-largeis 3072,text-embedding-3-smallis 1536, the open-source MiniLM models are 384,bge-largeis 1024. Vector type isvector(N)— once chosen, changing it requires a rewrite. Higher dimensions cost more storage, more index memory, and more query time. -
Create the table and index together:
CREATE EXTENSION IF NOT EXISTS vector; CREATE TABLE documents ( id bigserial PRIMARY KEY, tenant_id uuid NOT NULL, content text NOT NULL, embedding vector(1536) NOT NULL, created_at timestamptz NOT NULL DEFAULT now() ); CREATE INDEX documents_embedding_hnsw ON documents USING hnsw (embedding vector_cosine_ops) WITH (m = 16, ef_construction = 64);mcontrols graph connectivity (16 is the documented default; 24-32 for higher recall at higher RAM cost).ef_constructioncontrols build quality (64 default; 128+ for better recall, slower builds). -
Tune query-time ef_search. This is the single most important runtime knob — it controls the breadth of the search:
SET hnsw.ef_search = 100; SELECT id, content FROM documents WHERE tenant_id = $1 ORDER BY embedding <=> $2 LIMIT 10;Default is 40. Higher recall at the cost of latency; benchmark with your data, your queries, and your latency budget — there is no universal best value.
-
Filter then search, when possible. Combining a tenant filter with an ANN search is the production reality. pgvector pushes pre-filters into the index walk via
WHERE— the planner picks between filtering during the walk and post-filtering after. Add a btree ontenant_idand confirm with EXPLAIN that the tenant predicate isn’t dragging in millions of irrelevant rows. -
Build the index after bulk load. A common mistake is creating the HNSW index on an empty table then bulk-loading. Build performance is much better if you load first and
CREATE INDEXafter — and you can parallelise it: setmax_parallel_maintenance_workers = 4andmaintenance_work_mem = '8GB'. For 50M vectors at 1536 dims, expect 2-6 hours on a well-sized host. -
Reindex when the distribution shifts. ANN indexes degrade as data drifts from the build-time distribution. Schedule
REINDEX INDEX CONCURRENTLY documents_embedding_hnswon a quarterly cadence for active corpora.
Common pitfalls
- Forgetting the operator class —
vector_l2_ops,vector_cosine_ops,vector_ip_opsmust match the operator you query with. Mismatch and the index is silently bypassed. - Memory: HNSW indexes don’t fit on disk-only servers — set
effective_cache_sizeand provision RAM to hold the graph. As a rule, 1.5x the raw vector storage size in RAM per index. - pgvector vectors are 4 bytes per dimension plus 8 bytes overhead — 1536 dims is 6160 bytes per row. Five million rows is 30 GB before any TOAST.
- pgvector 0.7+ supports
halfvec(2 bytes per dim) for half the storage with minor recall loss; useful past 1024 dims. - Logical replication replicates vectors as text by default — make sure publisher and subscriber agree on the extension version and
binary = trueon the subscription.
In the engagements we run, pgvector replaces the separate vector database for almost every RAG workload up to about 100 million vectors. We size disk for 1.5x raw, RAM for the active index, and tune hnsw.ef_search per query path — chat retrieval and semantic search have different latency budgets. Behind it we pair pgvector with JSONB indexing for the metadata side and pg_stat_statements for the regression watch. For the operating model behind a production AI/data stack, see managed operations.