Build a hybrid RAG pipeline (pgvector + FTS + RRF)
Implement ingestion and retrieval combining pgvector cosine similarity with Postgres tsvector BM25/FTS via Reciprocal Rank Fusion.
Model Answer & Explanation
-- RRF Fusion in SQL (k = 60)
WITH vec AS (
SELECT id, ROW_NUMBER() OVER (ORDER BY embedding <=> $1) AS r
FROM chunks WHERE tenant_id = $3 ORDER BY r LIMIT 20
), fts AS (
SELECT id, ROW_NUMBER() OVER (ORDER BY ts_rank_cd(tsv, plainto_tsquery($2)) DESC) AS r
FROM chunks WHERE tenant_id = $3 AND tsv @@ plainto_tsquery($2) LIMIT 20
)
SELECT COALESCE(vec.id, fts.id) AS id,
COALESCE(1.0/(60+vec.r), 0) + COALESCE(1.0/(60+fts.r), 0) AS score
FROM vec FULL OUTER JOIN fts USING (id)
ORDER BY score DESC LIMIT 8; Store chunks in Postgres with content, metadata JSONB, tsvector (generated column + GIN), and embedding vector(1536) (HNSW index). At query time, filter by tenant_id first, fetch top 20 vector hits and top 20 FTS hits, fuse ranks with score = sum(1 / (60 + rank)), and return top 5–8 chunks with source metadata.