Skip to content

pgvector similarity search on PostgreSQL

Run vector similarity search in PostgreSQL with pgvector — HNSW vs IVFFlat, dimensionality, indexing trade-offs, and operational sizing for RAG workloads.

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

  1. Pick the dimension and stick to it. OpenAI’s text-embedding-3-large is 3072, text-embedding-3-small is 1536, the open-source MiniLM models are 384, bge-large is 1024. Vector type is vector(N) — once chosen, changing it requires a rewrite. Higher dimensions cost more storage, more index memory, and more query time.

  2. 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);

    m controls graph connectivity (16 is the documented default; 24-32 for higher recall at higher RAM cost). ef_construction controls build quality (64 default; 128+ for better recall, slower builds).

  3. 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.

  4. 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 on tenant_id and confirm with EXPLAIN that the tenant predicate isn’t dragging in millions of irrelevant rows.

  5. 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 INDEX after — and you can parallelise it: set max_parallel_maintenance_workers = 4 and maintenance_work_mem = '8GB'. For 50M vectors at 1536 dims, expect 2-6 hours on a well-sized host.

  6. Reindex when the distribution shifts. ANN indexes degrade as data drifts from the build-time distribution. Schedule REINDEX INDEX CONCURRENTLY documents_embedding_hnsw on a quarterly cadence for active corpora.

Common pitfalls

  • Forgetting the operator class — vector_l2_ops, vector_cosine_ops, vector_ip_ops must 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_size and 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 = true on 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.