Terminal window showing a SQL nearest-neighbor query next to a database table of text chunks and vector columns

pgvector for RAG: Practical Setup and Pitfalls

The first time pgvector returns the wrong rows, it is almost never a bug in pgvector. It is a distance operator that does not match the index, a filter applied after an approximate scan, or an embedding column that quietly mixes two models. Those are all fixable in an afternoon once you know where to look, and most of them are documented in the project’s README.

pgvector for RAG means storing chunk embeddings in PostgreSQL with the open-source pgvector extension and retrieving nearest neighbors with ordinary SQL. It is a strong default when your application data already lives in Postgres and your corpus is in the range a single well-sized database handles comfortably. This guide walks through a schema, indexes, filtered search, and a hybrid query, with the traps flagged. For a broader look at alternatives, see our vector database comparison for RAG; for background on the vectors themselves, read what embeddings are in AI.

A schema that survives re-embedding

Start by assuming you will change your chunker and your embedding model at least once. Record both on every row so you can re-index selectively, and keep the source document ID so deletions are one statement.

CREATE EXTENSION IF NOT EXISTS vector;

CREATE TABLE chunks (
  id               bigserial PRIMARY KEY,
  doc_id           bigint NOT NULL,
  tenant_id        int    NOT NULL,
  chunk_index      int    NOT NULL,
  chunk_text       text   NOT NULL,
  embedding        vector(1536) NOT NULL,   -- must equal your model's dimension
  embedding_model  text   NOT NULL,
  chunker_version  text   NOT NULL,
  valid_to         timestamptz,             -- NULL = current
  tsv tsvector GENERATED ALWAYS AS (to_tsvector('english', chunk_text)) STORED
);

The dimension 1536 is only an example; use whatever your embedding model returns, and never insert vectors from a different model into the same column. Mixed models produce distances that look plausible and mean nothing. If you must run two models during a migration, use two columns or two tables and cut over once the new one is complete. How to choose boundaries for chunk_text is covered in RAG chunking strategies.

Dimension limits matter at index time. The README states that the vector type can be indexed up to 2,000 dimensions, with halfvec supporting up to 4,000, and half-precision storage can shrink your working set (pgvector README).

Pick one distance operator and match the index to it

pgvector provides L2 distance (<->), cosine distance (<=>), and negative inner product (<#>). Which one is correct depends on how your embedding model was trained; most text embedding providers document cosine or inner product for normalized vectors. Choose once, and build the index with the matching operator class, otherwise the planner will not use it and your queries will quietly fall back to exact scans.

-- cosine distance, matching vector_cosine_ops
CREATE INDEX CONCURRENTLY chunks_embedding_hnsw
  ON chunks USING hnsw (embedding vector_cosine_ops);

SELECT id, chunk_text, embedding <=> $1 AS distance
FROM chunks
WHERE tenant_id = $2 AND valid_to IS NULL
ORDER BY embedding <=> $1
LIMIT 20;

Two details trip people up. <#> returns the negative inner product because Postgres index scans only support ascending order, so flip the sign if you want a similarity. And always sort by the raw distance expression; wrapping it in 1 - (...) in the ORDER BY prevents index use.

HNSW or IVFFlat: how to choose and what to tune

pgvector offers two approximate index types. HNSW builds a multi-layer graph (the technique comes from Malkov and Yashunin’s HNSW paper) and generally gives a better speed-recall tradeoff, at the cost of slower builds and more memory. IVFFlat clusters vectors into lists and searches only some of them; it builds faster and uses less memory but must be created after the table holds representative data.

  • HNSW build parameters: m (default 16) and ef_construction (default 64). Raising them improves recall and slows index build and inserts.
  • HNSW query parameter: hnsw.ef_search (default 40). Raise it per transaction with SET LOCAL when recall matters more than latency.
  • IVFFlat parameters: lists at build time and ivfflat.probes at query time (default 1). The README suggests starting probes around the square root of lists.
  • Build memory: HNSW builds are far faster when the graph fits in maintenance_work_mem; the build prints a notice when it no longer fits.

A sensible default for RAG is HNSW with cosine operators and an ef_search you tune against a labeled query set, not against intuition. Measure recall by comparing approximate results to an exact scan (just drop the index in a test copy) on a few hundred real questions.

Filtered search without empty results

This is the pitfall that bites production RAG hardest. With an approximate index, the README explains, filtering is applied after the index is scanned: if a condition matches 10% of rows and hnsw.ef_search is 40, you get about four matching rows on average. For a rare tenant you may get none.

Your options, from simplest to most structural:

  1. Enable iterative scans (pgvector 0.8.0 and later). SET hnsw.iterative_scan = strict_order; keeps scanning more of the index until enough rows pass the filter or hnsw.max_scan_tuples (default 20,000) is reached. relaxed_order is faster but may return results slightly out of order.
  2. Partial indexes when you filter by a few well-known values, such as a handful of product lines.
  3. Partitioning by tenant or another high-value key when you filter by many distinct values; the README recommends list partitioning or separate tables for tenant isolation.
  4. A btree index on the filter column so the planner can choose an exact scan when the filter is very selective, which gives perfect recall.

Design the filter fields before you ingest, not after; our guide to metadata filters for RAG covers ACL, versioning, and freshness fields in depth. Treat tenant isolation as a security control and test it with a rare-tenant query on every release.

Hybrid retrieval inside one SQL statement

Because the chunk text, tsvector, and embedding sit in one table, hybrid search is a query rather than a second system. The pgvector README points to Postgres full-text search for the keyword side and mentions reciprocal rank fusion or a cross-encoder for combining results. A compact RRF version looks like this:

WITH dense AS (
  SELECT id, row_number() OVER (ORDER BY embedding <=> $1) AS r
  FROM chunks WHERE tenant_id = $2
  ORDER BY embedding <=> $1 LIMIT 40
), sparse AS (
  SELECT c.id,
         row_number() OVER (ORDER BY ts_rank_cd(c.tsv, q) DESC) AS r
  FROM chunks c, websearch_to_tsquery('english', $3) q
  WHERE c.tenant_id = $2 AND c.tsv @@ q
  ORDER BY ts_rank_cd(c.tsv, q) DESC LIMIT 40
)
SELECT id, sum(1.0 / (60 + r)) AS score
FROM (SELECT * FROM dense UNION ALL SELECT * FROM sparse) t
GROUP BY id ORDER BY score DESC LIMIT 10;

The constant 60 is a conventional smoothing value, not a law; sweep it on your own questions. Language configuration matters on the keyword side (see the PostgreSQL full-text search documentation). The conceptual background, including why exact identifiers need a lexical channel, is in hybrid search for RAG, and the shortlist this query produces is a good input for a reranker.

Ingestion habits that save you later

  • Batch inserts rather than row-by-row, and load bulk data before building an IVFFlat index.
  • Build indexes concurrently on live tables so writes are not blocked, and schedule index builds with enough memory.
  • Upsert by (doc_id, chunk_index, chunker_version) and delete stale chunks for a document in the same transaction as the new insert, so readers never see half a document.
  • Store the embedding model name per row and add a check in your ingestion job that rejects a mismatch.
  • Use VACUUM and monitor bloat after heavy updates; the README notes that dead tuples can reduce the results an index scan returns.

A pitfall checklist before you call it done

  • Confirm with EXPLAIN that the nearest-neighbor query uses the vector index.
  • Compare approximate against exact results on real questions and record recall.
  • Test filtered queries for the smallest tenant and the narrowest version filter.
  • Verify embedding_model is uniform in every column you query.
  • Measure latency with production-like concurrency and a warm cache, from the application host.
  • Write the re-embedding runbook before you need it.

When results are still odd, step back to the staged diagnostic in RAG failure modes, and score retrieval with the methods in the RAGAS evaluation guide so changes to ef_search or chunk size are judged by data.

Signs you are outgrowing a single Postgres

pgvector is easy to like because it removes a system. It is time to reassess when index builds no longer fit your maintenance windows, when memory for the working set strains the instance that also serves your transactional traffic, or when you need retrieval features your team keeps re-implementing in SQL. At that point compare dedicated engines using the bake-off in our vector database comparison rather than migrating on reputation. If an agent is the consumer, wrap the query behind one stable tool, as the agent harness overview recommends for any external capability, so a later backend change is invisible to the model.

FAQ

Is pgvector good enough for RAG in production?
For many applications, yes, particularly when your data already lives in Postgres and you want transactions and joins alongside retrieval. You are responsible for index tuning, memory for builds, and testing filtered queries with realistic data and concurrency.

Should I use HNSW or IVFFlat for RAG?
HNSW is the usual starting point because it typically offers a better speed and recall tradeoff, though builds are slower and use more memory. IVFFlat builds faster and is lighter, but it should be created after representative data is loaded and needs probes tuned.

Why does my filtered pgvector query return fewer rows than LIMIT?
With approximate indexes the filter is applied after the index scan, so many of the scanned candidates may fail it. Enable iterative index scans on pgvector 0.8.0 or later, or use partial indexes, partitioning, or an exact scan for very selective filters.

Which distance operator should I use?
Use the one your embedding model is designed for, usually cosine or inner product on normalized vectors. Create the index with the matching operator class and order by the raw operator expression so the planner can use the index.

Can pgvector do hybrid search?
Yes. Combine it with PostgreSQL full-text search over a tsvector column and merge the ranked lists, for example with reciprocal rank fusion in SQL, then optionally rerank the shortlist with a cross-encoder.

What happens when I change my embedding model?
You must re-embed the affected chunks and avoid mixing models in one vector column. Record the model name per row, build the new embeddings in a separate column or table, validate retrieval quality, and then switch queries over.

Related reading

About Mudasir Syed

Check Also

GPU server rack in a data center running an open-weight LLM inference service

vLLM Serving Guide for Production LLM APIs

vLLM serving means running an open-weight model behind an HTTP server where the engine, not …

Leave a Reply