Skip to main content

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.

Official Reference

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.

Follow-up Interview Question · Why can filtering by tenant_id after an HNSW ANN limit 20 return fewer than 20 results?

Module Context & References

Applied AI · Practice engineering drills Hands-on RAG, structured extraction, eval harness and agent reliability drills
Personal Notes · Markdown

Technologies & Interview Topics Covered

Switch between short-term interview tracks and long-term 80/20 engineering depth to practice JavaScript internals, React rendering and hooks, timed frontend machine coding UI challenges, MeetaPro FG300, Blind 75 & NeetCode 150 DSA patterns, Python & FastAPI APIs, PostgreSQL query optimization & MVCC, Redis caching, Applied AI RAG pipelines & evaluations, and distributed system design.