Topics / 🧠 LLM Engineering / 🔎 Level 26: RAG, Tools & Agents

Python exercise · about 5 minutes · free

Hybrid Search with Rank Fusion

Keyword search nails 'KL-1001'. Vector search nails 'housing loan'. Advanced RAG uses both and merges the rankings.

Reciprocal rank fusion (RRF) merges several ranked lists without comparing their raw scores. Each document earns 1 / (k + rank) from every list it appears in (rank starts at 1, k is usually 60). Add them up and sort.

📚 Go deeper: LLM Course: Advanced RAG

Table. two rankings: rank, keyword, vector; 1 | prepay | late-fee; 2 | late-fee | emi-date; 3 | kyc | prepay. Operation: Σ 1/(60 + rank). Result fused: rank, doc; 1 | late-fee; 2 | prepay; 3 | emi-date; 4 | kyctwo rankingsrankkeywordvector1prepaylate-fee2late-feeemi-date3kycprepayfusedrankdoc1late-fee2prepay3emi-date4kycΣ 1/(60 + rank)
Your quest: Write rrf(rankings, k=60): rankings is a list of ranked id lists. Return all ids sorted by fused score, highest first.
Try it now Runs in your browser. No sign-in needed. Ctrl+Enter to run.
Hintscores = {}; for ranking in rankings: for rank, doc in enumerate(ranking, 1): scores[doc] = scores.get(doc, 0) + 1 / (k + rank). Return sorted(scores, key=scores.get, reverse=True).
Output appears here.

Open it in the full course → Free with Google: saves your progress and unlocks 627 lessons.

In this level you'll learn:
More in Level 26: RAG, Tools & Agents

Share on LinkedIn