Merge several retrievers' rankings with reciprocal rank fusion

Hybrid search often runs a keyword retriever and a vector retriever, then has to merge two rankings whose scores live on different scales. Reciprocal rank fusion ignores the scores and uses only positions.

Write rrf_fuse(rankings, k). rankings is a list of ranked lists of document ids (strings), best first. A document at 1-based rank r in a list gets 1 / (k + r) from that list; a document missing from a list gets nothing from it. Its fused score is the sum over lists.

Return a list of (doc_id, score) tuples, score rounded to 6 decimals, sorted by score descending. Break ties by doc_id ascending.

Signaturedef rrf_fuse(rankings, k)

Example

rrf_fuse([["a", "b"], ["b", "c"]], 60) gives [("b", 0.032522), ("a", 0.016393), ("c", 0.016129)].

Understand the idea

When two retrievers give scores on different scales, you cannot simply add the scores. Reciprocal rank fusion ignores the scores and looks only at positions: a document near the top of a list gets a big share, one further down gets less, and appearing in several lists adds up. The constant k softens the gap between rank 1 and rank 2. Worked example with k = 60: lists ['x', 'y', 'z'] and ['z', 'x']. x: 1 / 61 + 1 / 62 = 0.016393 + 0.016129 = 0.032522. z: 1 / 63 + 1 / 61 = 0.015873 + 0.016393 = 0.032266. y: 1 / 62 = 0.016129. Order: x, z, y. Rule: score(d) = sum over lists containing d of 1 / (k + r), where r is the 1-based rank in that list; documents missing from a list get nothing from it; round to 6 decimals; sort by score descending and break ties by doc id ascending. Starting ranks at 0 shifts every score. RRF is a common default for hybrid keyword plus vector search in RAG pipelines.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: examplerrf_fuse([['a', 'b'], ['b', 'c']], 60)
  • Sample 2: three retrievers, small krrf_fuse([['d1', 'd2', 'd3'], ['d3', 'd1'], ['d2', 'd4', 'd1']], 1)
  • Test 3: tie broken by idrrf_fuse([['x', 'y'], ['y', 'x']], 10)
  • Test 4: single listrrf_fuse([['q', 'p', 'r']], 0)