Sub topic 6
Merging Ranked Lists with Reciprocal Rank Fusion
This chapter assumes you know how a basic RAG pipeline works, how vector and BM25 search return ranked results, and how to read Python. You will learn how to merge several ranked lists into one, which you need after multi-query expansion.
The merging problem
Multi-query expansion gives you several searches for one question. Each search returns its own ranked list of document ids. You need one list to pass to the model.
Merging by raw score does not work well. A cosine similarity of 0.82 from a vector index and a BM25 score of 14.3 are on different scales. Even two vector searches with different queries can produce scores that are not comparable. Rank is the one thing every list has in common.
How reciprocal rank fusion works
Reciprocal rank fusion (RRF) is a method that merges ranked lists using only each document's position in each list. A document at position rank (starting at 1) earns 1 / (k + rank) from each list it appears in. Its final score is the sum of those contributions.
- A document near the top of one list earns a large contribution.
- A document found by several lists collects several contributions.
- A document missing from a list earns nothing from it.
The constant k controls how much the top positions dominate. A small k makes rank 1 far more valuable than rank 2. A larger k flattens the curve. The value 60 is a common default, and it works acceptably in many cases without tuning.
Implementation
def reciprocal_rank_fusion(rankings: list[list[str]], k: int = 60) -> list[str]:
scores: dict[str, float] = {}
for ranking in rankings:
for rank, doc_id in enumerate(ranking, start=1):
scores[doc_id] = scores.get(doc_id, 0.0) + 1.0 / (k + rank)
return sorted(scores, key=scores.get, reverse=True)
print(reciprocal_rank_fusion([["a", "b", "c"], [“b”, "c", "d"]]))Wait: the smart quotes above are not valid Python. Use this corrected version:
def reciprocal_rank_fusion(rankings: list[list[str]], k: int = 60) -> list[str]:
scores: dict[str, float] = {}
for ranking in rankings:
for rank, doc_id in enumerate(ranking, start=1):
scores[doc_id] = scores.get(doc_id, 0.0) + 1.0 / (k + rank)
return sorted(scores, key=scores.get, reverse=True)
print(reciprocal_rank_fusion([["a", "b", "c"], ["b", "c", "d"]]))The function walks each list, adds the reciprocal term to a running total per document id, and sorts by total.
Worked example
With k = 60, the two lists ["a", "b", "c"] and ["b", "c", "d"] score as follows.
| Document | Contribution from list 1 | Contribution from list 2 | Total |
|---|---|---|---|
| a | 1/61 = 0.01639 | none | 0.01639 |
| b | 1/62 = 0.01613 | 1/61 = 0.01639 | 0.03252 |
| c | 1/63 = 0.01587 | 1/62 = 0.01613 | 0.03200 |
| d | none | 1/63 = 0.01587 | 0.01587 |
The output is ['b', 'c', 'a', 'd']. Document a was first in one list, but b and c were ranked well by both, so they win.
Using it with multi-query search
The merge slots in after the per-query searches. The function below searches with the original question and the model-written variants, then fuses the results.
from typing import Callable
def multi_query_search(
question: str,
llm: Callable[[str], str],
search: Callable[[str, int], list[str]],
n: int = 3,
top_k: int = 5,
) -> list[str]:
prompt = (
f"Write {n} different search queries for the question below, "
f"one per line, with no numbering.\n\n{question}"
)
variants = [q.strip() for q in llm(prompt).splitlines() if q.strip()][:n]
queries = [question] + variants
rankings = [search(q, top_k) for q in queries]
return reciprocal_rank_fusion(rankings)[:top_k]It reuses reciprocal_rank_fusion from above. The same function also merges a vector list with a BM25 list for one query.
Common errors
- Duplicate ids inside one list. The same id counted twice in a single list inflates its score. Deduplicate each list first.
- Inconsistent ids. If one index returns chunk ids and another returns document ids, the same content is counted as different items. Use one id scheme.
- Lists of very different lengths. Fetch the same
top_kfrom each search so no list contributes far more entries than the others. - Ties. Equal scores fall back to insertion order in Python's stable sort. Add an explicit tie-break if you need reproducible output.
- Ignoring quality. RRF treats all lists equally. A poor query variant can still push weak documents upward.
Exercise
With k = 60, document "x" is ranked 1st in one list and absent from a second list. Document "y" is ranked 3rd in both lists. Which scores higher?
Show answer
"y" scores higher. "x" gets 1/61 = 0.01639. "y" gets 1/63 + 1/63 = 0.03175. Appearing in both lists outweighs a single top position.