Course
AI · Module 05: Production RAG SystemsTutorial 14 of 21
AI Course·~1.5 hrs

5.2 Hybrid Search (BM25 + Vector), RRF & Cross-Encoder Reranking

Upgrade naive vector search to Google-grade retrieval quality: fuse BM25 keyword search with dense vectors using Reciprocal Rank Fusion (RRF) in a single SQL query, then sharpen precision with a Cross-Encoder Reranker.

01 Intuition: Plain-English mental model
02 Visuals: Step-by-step diagrams
03 Practice: Clean examples & tradeoffs

1. Why Pure Vector Search Fails on Exact Identifiers

Try searching a pure vector-only RAG bot for:

  • An exact error code: ORA-01555 or ECONNRESET
  • A product SKU or part number: TPS7A4700RGWT
  • A function or flag name: --max-old-space-size or hnsw.iterative_scan

Dense embeddings compress text into smooth semantic concepts ("database snapshot error"), often washing out exact alphanumeric tokens! Meanwhile, classical Lexical Search (BM25 / PostgreSQL Full-Text Search) nails ORA-01555 in 1 ms — but misses conceptual paraphrases.

Production Solution: Never choose one — run both in parallel (Hybrid Search), fuse their rankings with Reciprocal Rank Fusion (RRF), and pass the top 25 candidates through a Cross-Encoder Reranker!

BM25 KEYWORDTop 50 Lexical HitsDENSE VECTORTop 50 Semantic HitsRRF MERGEΣ 1 / (60 + rank)Top 25 Fused CandidatesCROSS-ENCODERJoint (Query, Doc)Deep Attention RerankTOP 5GOLD CHUNKS→ LLM Prompt
Figure: Bi-Encoders + BM25 cast a fast 5ms wide net (Recall), while a Cross-Encoder Reranker scores the Top 25 with full joint attention (Precision).

2. Reciprocal Rank Fusion (RRF): Zero-Tuning Score Merging!

How do you combine a BM25 score (unbounded float like 14.82) with a Cosine Similarity score (0.831)? Naive weighted sums (0.7 * cos + 0.3 * bm25) break constantly because BM25 scores swing wildly from 1.2 to 45.0 depending on query length!

Reciprocal Rank Fusion (RRF) ignores raw score scales completely and fuses purely by rank position (1, 2, 3, ...):

TEXT
RRF_Score(doc) =  1 / (k + rank_vector)  +  1 / (k + rank_bm25)     (standard smoothing k = 60)
  • Document X: Rank #2 in Vector + Rank #3 in BM25 → 1/62 + 1/63 = 0.0161 + 0.0159 = 0.0320 (Shoots to #1!)
  • Document Y: Rank #1 in Vector + missing in BM25 → 1/61 + 0 = 0.0164
  • Why k = 60 works like magic: Zero hyperparameter calibration needed, immune to score-scale outliers, and rewards documents corroborated by both semantic meaning and exact keywords!

3. Bi-Encoders vs. Cross-Encoder Rerankers (Recall vs. Precision)

Why do we retrieve Top 25 via Hybrid RRF and then run a Reranker (Cohere Rerank 3.5, Voyage rerank-2, BAAI/bge-reranker-v2-m3) to pick the final Top 5?

ArchitectureHow It Computes RelevanceSpeed on 10M DocsPrecisionRole in Funnel
Bi-Encoder (Embeddings)Encodes Query and Doc separately into 2 single vectors; compares via 1 dot product3 ms (pre-indexed!)Good (misses subtle negation & multi-word relationships)Stage 1: Wide Recall (Top 50)
Cross-Encoder (Reranker)Concatenates [CLS] Query [SEP] Doc into one Transformer so every query token attends directly to every document token!Impossible (10 hours!) — must run only on Top 25 (~60 ms!)🏆 Gold-Standard Precision (+15%–28% NDCG!)Stage 2: Surgical Precision (Top 5)

4. Wire-Level Trace: Watching Hybrid RRF + Reranking Rescue a Failed Query

Tracing Hybrid RRF + Cross-Encoder Reranking on a Technical Query
Interactive LLM Pipeline Tracer · Step 1 of 3 (1. Pure Vector Search Alone Misses Exact Error '529')
Wire Telemetry:latency=68ms
1→q = "Fix error 529 in Anthropic streaming without duplicate charges"
2→vec_hits = pgvector_top_50(embed(q)) # Finds retry/idempotency docs
3bm25_hits = postgres_fts_top_50(q) # Pins exact "529" status docs!
4candidates = reciprocal_rank_fusion(vec_hits, bm25_hits, top_n=25)
5gold_top_5 = reranker.rerank(query=q, docs=candidates, top_n=5)
Dense Vector Top-2SEMANTIC ONLY
#1Stripe Idempotency Keys Guide (sim=0.84)
#2 Handling OpenAI 429 Rate Limits (sim=0.82)  // Missed Claude '529' doc at #14!
What's Happening: Dense vectors matched 'streaming without duplicate charges' well, but ranked OpenAI's 429 doc ahead of Anthropic's specific 529 Overloaded doc!

5. Copy-Paste Production SQL: Single-Query Hybrid Search + RRF in PostgreSQL!

One of the cleanest patterns in modern backend engineering — dense HNSW + lexical full-text + RRF fusion in ONE single round-trip to PostgreSQL:

SQL
WITH vector_matches AS (
    SELECT chunk_id,
           ROW_NUMBER() OVER (ORDER BY embedding <=> $1::halfvec) AS vec_rank
    FROM doc_chunks
    WHERE tenant_id = $2
    ORDER BY embedding <=> $1::halfvec
    LIMIT 50
),
keyword_matches AS (
    SELECT chunk_id,
           ROW_NUMBER() OVER (ORDER BY ts_rank_cd(tsv, websearch_to_tsquery('english', $3)) DESC) AS kw_rank
    FROM doc_chunks
    WHERE tenant_id = $2
      AND tsv @@ websearch_to_tsquery('english', $3)
    LIMIT 50
),
rrf_fused AS (
    SELECT COALESCE(v.chunk_id, k.chunk_id) AS chunk_id,
           COALESCE(1.0 / (60 + v.vec_rank), 0.0) +
           COALESCE(1.0 / (60 + k.kw_rank), 0.0) AS rrf_score
    FROM vector_matches v
    FULL OUTER JOIN keyword_matches k ON v.chunk_id = k.chunk_id
    ORDER BY rrf_score DESC
    LIMIT 25
)
SELECT c.chunk_id, c.breadcrumb, c.content, r.rrf_score
FROM rrf_fused r
JOIN doc_chunks c USING (chunk_id)
ORDER BY r.rrf_score DESC;

Adding Stage-2 Reranking in Python & TypeScript

SDK:
import voyageai
from openai import OpenAI

vo = voyageai.Client()
oa = OpenAI()

def rerank_and_answer(question: str, rrf_candidates: list[dict]) -> str:
  # 1. Cross-Encoder Rerank: 25 RRF candidates -> Top 5 high-precision chunks (~60ms)
  reranked = vo.rerank(
      query=question,
      documents=[c["content"] for c in rrf_candidates],
      model="rerank-2-lite",
      top_k=5,
  )
  top_chunks = [rrf_candidates[r.index] for r in reranked.results if r.relevance_score > 0.25]

  # 2. Grounded generation on the distilled Top 5
  context = "\n\n".join(f"[{c['chunk_id']}] {c['content']}" for c in top_chunks)
  return oa.responses.create(
      model="gpt-4o-mini",
      instructions="Answer strictly using the cited [chunk_id] passages.",
      input=f"{context}\n\nQuestion: {question}",
  ).output_text

6. What Breaks in Production (War Stories)

  1. Using plainto_tsquery With AND Only in PostgreSQL FTS: In Postgres, plainto_tsquery('english', 'how do I fix error 529 today') requires every single word (fix & error & 529 & today) to appear in the chunk — returning 0 rows just because the doc didn't contain the word "today"! Use websearch_to_tsquery (or paradedb / pg_search true BM25) for much smarter lexical recall.
  2. Skipping a Minimum Reranker Score Threshold: Even if the user asks "Who won IPL 2026?" against your Stripe billing docs, top_k=5 still returns the 5 least-bad billing chunks (relevance_score = 0.01)! Drop chunks below a calibrated floor (e.g., < 0.15) so your LLM cleanly sees <sources></sources> and abstains instead of hallucinating from noise!
  3. Sending 2,000-Token Chunks Into a 512-Token Reranker: Older cross-encoders silently truncate inputs at 512 tokens! Use modern long-context rerankers (rerank-v3.5 4k context, voyage-rerank-2 4k–8k) and keep chunks concise.

Module 5.2 Mastery Check — Hybrid Search, RRF & Reranking

Q1.Why does Reciprocal Rank Fusion (`RRF`) use rank positions (`1 / (60 + rank)`) instead of adding raw BM25 and Cosine scores directly?
Q2.Why can't we skip Embeddings/BM25 altogether and run a Cross-Encoder Reranker directly across all 5,000,000 chunks in our database?
Q3.Which type of user query benefits MOST from adding BM25 lexical search alongside dense vector search?
Q4.Why should you apply a minimum relevance threshold after Cross-Encoder reranking before passing chunks to the LLM?

Keep Exploring: Related Lessons & Tools

All Courses →