Sub topic 6
Merging ranked lists with reciprocal rank fusion
This chapter assumes you can read Python, you know how vector search and keyword (BM25) search return ranked results, and you have seen the multi-query idea from the previous chapter. Here you learn how to combine several ranked lists into one list, and why a rank-based method is usually the safest way to do it.
Why merging is a problem
Once you search with several phrasings of a question, or with both a vector index and a keyword index, you hold several ranked lists of document ids. You need one list to pass to the generator.
The obvious approach is to add up the scores each search returned. That fails because the scores are not comparable:
- BM25 scores are unbounded and depend on corpus statistics and query length.
- Cosine similarity scores sit between -1 and 1, and often cluster in a narrow band such as 0.70 to 0.85.
- Different query phrasings produce different score distributions, even on the same index.
You could normalize each list (min-max, z-score) before adding. That works only if each list's distribution is well behaved. One outlier hit can squash every other score in a min-max normalization.
Reciprocal rank fusion (RRF) avoids the problem by ignoring scores. It uses only each document's position in each list.
The formula
For a document d and a set of ranked lists R, the RRF score is:
score(d) = sum over lists r in R where d appears of 1 / (k + rank_r(d))Ranks start at 1. The constant k is usually 60, the value from the original paper by Cormack, Clarke and Buettcher (2009). Documents are then sorted by score, highest first.
Two properties follow directly:
- A document gains from every list that contains it, so agreement between lists pushes a document up.
- A document's contribution from one list shrinks smoothly with rank. It never drops to zero for being low in a list, and it never dominates for being first.
A minimal 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"]]))This prints ['b', 'c', 'a', 'd']. Here is the arithmetic with k = 60:
| Document | List 1 rank | List 2 rank | Score |
|---|---|---|---|
| b | 2 | 1 | 1/62 + 1/61 = 0.03252 |
| c | 3 | 2 | 1/63 + 1/62 = 0.03200 |
| a | 1 | absent | 1/61 = 0.01639 |
| d | absent | 3 | 1/63 = 0.01587 |
Document a was first in list 1, but b and c appear in both lists, so they outrank it. That is the behavior you want when several phrasings of the same question agree on what is relevant.
What the constant k does
The constant k controls how much the very top ranks matter compared with the rest of the list.
- With a small
k, such as 0 or 1, the gap between rank 1 and rank 2 is large. A single first place can beat a document that appears in several lists at mediocre ranks. - With a large
k, such as 60, the curve is flat. Rank 1 and rank 5 contribute almost the same amount, so the number of lists a document appears in matters more than its exact positions.
You can check this directly. The helper below returns the winner for a given k:
def rrf_scores(rankings: list[list[str]], k: int = 60) -> dict[str, float]:
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 scores
def winner(rankings: list[list[str]], k: int) -> str:
scores = rrf_scores(rankings, k)
return max(scores, key=scores.get)
lists = [["top", "x", "both"], ["y", "z", "both"]]
print(winner(lists, k=0)) # top
print(winner(lists, k=60)) # bothWith k = 0, top scores 1.0 and both scores 1/3 + 1/3 = 0.67, so top wins. With k = 60, top scores 0.0164 and both scores 2/63 = 0.0317, so both wins. Use max here rather than a sort, because with k = 0 the documents top and y tie at 1.0.
In practice, 60 is a reasonable default. Tune it only if you have an evaluation set (covered in a later chapter), and expect small effects.
Using RRF in a pipeline
RRF fits at two points in a RAG pipeline.
- Fusing multi-query results. This is the case in the previous chapter's
multi_query_search. Each query variant gets its own search, and the lists are fused. The original question stays in the set of queries so a poor rewrite cannot remove the user's own wording. - Fusing hybrid search. A vector index and a BM25 index return lists for the same query. Many search engines and vector databases offer RRF as a built-in way to combine them, so check your system's documentation before writing your own.
Here is the second case in a few lines. Both searches are plain functions that return document ids, ordered best first:
from typing import Callable
def hybrid_search(
query: str,
vector_search: Callable[[str, int], list[str]],
keyword_search: Callable[[str, int], list[str]],
candidates: int = 20,
top_k: int = 5,
) -> list[str]:
rankings = [
vector_search(query, candidates),
keyword_search(query, candidates),
]
return reciprocal_rank_fusion(rankings)[:top_k]Fetch more candidates from each search than you finally keep. A document ranked 12th by both searches can still be a strong fused result, but only if both lists reach that deep.
Common errors and edge cases
Duplicates inside one list. If a list contains the same id twice, for example because you searched chunks and mapped them to parent document ids, the document is counted twice from that list. Deduplicate each list first, keeping the first occurrence:
def dedupe(ranking: list[str]) -> list[str]:
return list(dict.fromkeys(ranking))Mismatched identifiers. RRF joins lists by id. If one index uses doc-12 and another uses 12, the same document is treated as two. Normalize ids before fusing.
Chunks versus documents. Decide whether you fuse at chunk level or document level, and be consistent. Fusing chunk ids from different chunking schemes will rarely produce matches.
Ties. Equal scores are common with short lists. Python's sorted is stable, so ties resolve to the order in which ids were first seen, which means the first list wins. If that matters, put your most trusted list first, or add an explicit tie-break.
Lists of different length. A list that returns 3 results and one that returns 20 are both valid inputs. A missing document simply contributes nothing from that list. This is a strength of RRF, but it also means a document absent from a list is not penalized for it.
Weighting. Plain RRF treats every list equally. If you trust one source more, multiply its contribution by a weight. The change is small:
def weighted_rrf(
rankings: list[list[str]], weights: list[float], k: int = 60
) -> list[str]:
scores: dict[str, float] = {}
for ranking, weight in zip(rankings, weights, strict=True):
for rank, doc_id in enumerate(ranking, start=1):
scores[doc_id] = scores.get(doc_id, 0.0) + weight / (k + rank)
return sorted(scores, key=scores.get, reverse=True)Weights add a tuning parameter, so add them only when evaluation shows a gain. A common case is giving the original question's list a weight of 2 and each rewritten variant a weight of 1.
Limits of RRF
RRF discards score information. If one list has a hit with a similarity of 0.99 and the next at 0.50, RRF still treats them as adjacent ranks. When a score gap carries real meaning, such as an exact match, RRF loses that signal.
RRF also cannot add relevance that no list contains. It reorders candidates and nothing more. If every query variant misses the right passage, fusion cannot recover it. For that, you need a better query, which the following chapters cover.
Finally, RRF does not judge relevance. It rewards agreement. A wrong passage that several variants retrieve can outrank a correct passage that only one variant finds. If this hurts you, a reranking model applied to the fused top candidates can reorder them by actual relevance to the question.
Summary of decisions
| Situation | Choice |
|---|---|
| Lists come from different scorers (BM25 plus vectors) | Use RRF with `k = 60` |
| Lists come from query variants of one question | Use RRF, and keep the original query in the set |
| One source is clearly more reliable | Try weighted RRF, and confirm with evaluation |
| Score gaps carry meaning | Consider score normalization or a reranker |
| Fused top results still look wrong | Rerank the top candidates, or improve the queries |
Exercise
Two searches return these lists: [m, n, o] and [o, m, p]. With k = 60, compute the RRF score for each document and give the final order. Which document comes first, and why?
Show answer
m = 1/61 + 1/62 = 0.01639 + 0.01613 = 0.03252. o = 1/63 + 1/61 = 0.01587 + 0.01639 = 0.03226. n = 1/62 = 0.01613. p = 1/63 = 0.01587. The order is m, o, n, p. Document m comes first because it appears near the top of both lists (ranks 1 and 2). Document o was first in list 2 but only third in list 1, so its total is slightly lower.
Exercise
A list returned by a chunk-level search contains the ids [d1, d1, d2]. What goes wrong if you pass it to reciprocalrankfusion unchanged, and how do you fix it?
Show answer
The id d1 is counted twice from the same list, at ranks 1 and 2, so it gets 1/61 + 1/62 from a single search and is inflated relative to documents found by other lists. Fix it by deduplicating each list before fusing, keeping the first occurrence, for example with list(dict.fromkeys(ranking)).