RAG on Postgres: hybrid vector and keyword search with pgvector and RRF
Build RAG retrieval inside the Postgres you already run: pgvector HNSW for meaning, full-text search for exact terms, and Reciprocal Rank Fusion to merge them.
Key figures
- 0.8.6
- pgvector release used (Jul 29)
- 2,000
- Max dims for an HNSW vector index
- 40
- Default hnsw.ef_search
Retrieval-augmented generation lives or dies on retrieval. Many teams reach for a dedicated vector database, but if your data already sits in Postgres, the pgvector extension plus Postgres's own full-text search can cover most workloads with one fewer system to operate. This tutorial builds a hybrid retriever: semantic search over embeddings, keyword search over a tsvector, and Reciprocal Rank Fusion (RRF) to combine them. You need Docker, Python 3.10+, psycopg 3 and an embedding model of your choice. Versions: PostgreSQL 18 and pgvector 0.8.6 (released 29 July 2026); use 0.8.6 or later, since recent point releases fixed HNSW vacuuming bugs.
1. Start Postgres with pgvector
docker run -d --name rag-db -p 5432:5432 \
-e POSTGRES_PASSWORD=dev --shm-size=1g pgvector/pgvector:pg18
pip install "psycopg[binary]" pgvector numpyThe larger shared-memory size matters later: if you raise maintenance_work_mem for faster index builds, the pgvector docs note that --shm-size must be at least as large, or parallel HNSW builds fail.
2. Create the schema
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE chunks (
id bigserial PRIMARY KEY,
doc_id text NOT NULL,
content text NOT NULL,
embedding vector(1024) NOT NULL,
tsv tsvector GENERATED ALWAYS AS (to_tsvector('english', content)) STORED
);
CREATE INDEX ON chunks USING hnsw (embedding vector_cosine_ops);
CREATE INDEX ON chunks USING gin (tsv);
CREATE INDEX ON chunks (doc_id);Set the vector dimension to whatever your embedding model returns. HNSW indexes on the vector type support up to 2,000 dimensions; for larger embeddings, store them as halfvec, which indexes up to 4,000. The generated tsv column keeps the keyword index in sync with content automatically. For bulk loads, insert first and create the HNSW index afterwards; builds are much faster when the graph fits in maintenance_work_mem.
3. Ingest documents
import numpy as np
import psycopg
from pgvector import Vector
from pgvector.psycopg import register_vector
def embed(texts: list[str]) -> list[list[float]]:
"""Call your embedding model here; it must return 1024-dim vectors."""
raise NotImplementedError
def ingest(conn, doc_id: str, chunks: list[str]) -> None:
for text, vec in zip(chunks, embed(chunks)):
conn.execute(
"INSERT INTO chunks (doc_id, content, embedding) VALUES (%s, %s, %s)",
(doc_id, text, Vector(np.array(vec, dtype=np.float32))),
)
conn = psycopg.connect("postgresql://postgres:dev@localhost:5432/postgres", autocommit=True)
register_vector(conn)Chunk on natural boundaries such as headings and paragraphs, keep chunks to a few hundred tokens, and store enough metadata (doc_id, section, updated time) to filter and cite later. Embed queries with the same model you used for documents.
4. Query with hybrid search and RRF
Each sub-query returns its top 20 candidates; RRF then scores each chunk as the sum of 1/(60 + rank) across the lists it appears in. The constant 60 is the conventional default and dampens the influence of any single list.
WITH semantic AS (
SELECT id, ROW_NUMBER() OVER (ORDER BY dist) AS rank
FROM (SELECT id, embedding <=> %(emb)s AS dist
FROM chunks ORDER BY embedding <=> %(emb)s LIMIT 20) s
),
keyword AS (
SELECT id, ROW_NUMBER() OVER (ORDER BY score DESC) AS rank
FROM (SELECT id, ts_rank_cd(tsv, q) AS score
FROM chunks, websearch_to_tsquery('english', %(q)s) q
WHERE tsv @@ q ORDER BY score DESC LIMIT 20) k
)
SELECT c.id, c.doc_id, c.content,
COALESCE(1.0 / (60 + s.rank), 0) + COALESCE(1.0 / (60 + k.rank), 0) AS rrf
FROM semantic s
FULL OUTER JOIN keyword k USING (id)
JOIN chunks c USING (id)
ORDER BY rrf DESC
LIMIT 5;Run it from Python with conn.execute(SQL, {"emb": Vector(np.array(embed([question])[0], dtype=np.float32)), "q": question}). websearch_to_tsquery accepts raw user input (quotes, OR, -term) without raising syntax errors, which makes it safe for a search box. Pass the top chunks, with their doc_ids, to the model and ask it to cite them.
5. Tune recall, not just speed
hnsw.ef_searchcaps results. It defaults to 40, so an HNSW query cannot return more than about 40 neighbours however high yourLIMIT.SET hnsw.ef_search = 100;trades speed for recall.- Filters can starve results. Approximate indexes filter after the index scan, so
WHERE doc_id = ...may leave too few rows. EnableSET hnsw.iterative_scan = relaxed_order;(orstrict_order), use the B-tree index for highly selective filters, or create partial indexes when there are only a few filter values. - Build parameters.
m(default 16) andef_construction(default 64) trade build time and memory for graph quality; change them only when your eval shows a recall problem.
Pitfalls and next steps
- Language matters. The
'english'configuration stems English words. Postgres's built-in parsers do not segment Chinese or Japanese text, so CJK keyword search needs an n-gram or language-aware extension. - Model changes mean re-embedding. Vectors from different embedding models are not comparable; version your embeddings and backfill before switching.
- Measure retrieval separately. Label 50 or so real questions with the chunks that answer them and track recall@5 before judging the generated answers.
Once retrieval scores well, try a cross-encoder re-ranker over the merged top 20, which pgvector's documentation suggests as an alternative to RRF.
Researched and drafted with AI assistance under editorial review. Report errors to support@aiseeker.dev.
Sources
This report synthesises the sources below. Primary sources are marked.
- [1]pgvector: Open-source vector similarity search for Postgres
pgvector (GitHub)2026.11.28Primary
- [2]pgvector CHANGELOG
pgvector (GitHub)2026.07.29Primary
- [3]pgvector-python
pgvector (GitHub)2026.11.28Primary
- [4]12.3. Controlling Text Search
PostgreSQL Documentation2026.11.28Primary