PREP WITH PROOF
Menu
AI & RETRIEVAL / PRACTICAL GUIDE

Reciprocal Rank Fusion Explained: Merge Hybrid Search Results in Python

Implement RRF with exact scores, candidate windows and deterministic ties. Run a Python lab covering duplicate IDs, missing candidates and 300 seeded ranking fixtures.

THE QUICK ANSWER

Reciprocal Rank Fusion sums 1/(rank_constant + rank) for each ranked list containing a document, with ranks starting at one. It merges positions instead of adding raw lexical and vector scores. Candidate windows, stable IDs, duplicate policy and tie handling affect the result. A correct fusion calculation still needs separate relevance evaluation.

Combine rankings without pretending their raw scores share a scale

A lexical retriever returns documents ordered by text relevance. A vector retriever returns another list ordered by similarity. Both may find useful material, but their score magnitudes do not automatically describe the same quantity. Adding a lexical score to a cosine similarity can make the larger numerical scale dominate without a meaningful weighting decision.

Reciprocal Rank Fusion, or RRF, offers a different starting point: combine the positions of documents in the ranked lists. You keep the order each retriever produced and give a document a contribution for each list in which it appears. The result is a new ordering over the supplied candidates.

This guide focuses on implementing and inspecting that merge. It complements the existing retrieval-metrics guide, which explains how to evaluate a ranking against relevance labels. The example here uses invented document IDs and exact rational arithmetic; it does not run a search engine, embed text or demonstrate an improvement in real retrieval quality.

A document receives one contribution from each retained list

For each document d, the unweighted score is the sum of 1 / (k + rank_i(d)) over lists containing d. Ranks start at 1; k is a rank constant. A missing document contributes zero for that list. The original RRF paper and current Elasticsearch documentation describe the rank-based formula. This guide applies it to finite candidate lists.

Use the rank constant to reason about the difference between positions, not as a synonym for the number of results. For one list, the ratio of first-place contribution to second-place contribution is (k + 2) / (k + 1). Raising k makes that ratio closer to one. This is arithmetic about position sensitivity; it is not a guarantee that a larger constant improves a particular query.

The lab uses 60 for its worked example and permits other positive integer constants. Keep that choice explicit in experiment records. The source paper used 60 in its reported setup, but its benchmark results are not measurements of your documents, queries or user task.

Source: Cormack, Clarke and Büttcher: original RRF paper, SIGIR 2009 ↗

Inspect a four-document example before reading the implementation

Let the lexical list be A, B, C and the vector list be B, D, A. Retain all three positions from each list and set the rank constant to 60. B receives contributions for positions two and one. A receives contributions for positions one and three. D and C each receive only one contribution.

The table contains the exact fractions and rounded decimal displays printed by the published lab. The implementation sorts using the exact fractions, not those rounded displays. In this fixture, B ranks above A because its second contribution is stronger. That statement explains the arithmetic for these invented lists; it does not assign semantic relevance to any of the IDs.

If you keep only the first result from each source before fusion, the candidate set becomes A and B. They tie at 1/61, and the fixture’s explicit lexical ID rule puts A first. This changes the outcome without changing the underlying full input lists. Candidate selection is part of the behavior you must record.

DocumentLexical rankVector rankExact fused scoreDecimal display
B21123/37820.032522475
A13124/38430.032266458
DAbsent21/620.016129032
C3Absent1/630.015873016

Keep the rank constant, candidate window and output size distinct

The rank constant changes contributions from retained positions. A per-source window decides how many ranked candidates participate. The final output size decides how many fused results reach the next stage. These are different controls. Azure’s documentation also distinguishes the RRF constant from the k used to request nearest neighbors.

In this implementation, window truncates each input list before contributions are added. fuse returns the whole ranked union; a caller can select rows[:output_size] afterward. If a relevant document is absent from every retained input window, this function has no mechanism to recover it. Increasing only the final output size cannot create a missing candidate.

For a real pipeline, name these values clearly in logs and experiments. A vector candidate request, an RRF source window and a context budget for an answer generator can all be called “top k” informally. Giving each one a separate name prevents an apparent fusion regression from being caused by a changed upstream retrieval budget.

Source: Azure AI Search: hybrid search ranking and the separate RRF constant ↗

Define document identity, duplicate handling and ties

Fusion needs stable identities shared across the input lists. If the same chunk appears as one ID in lexical search and another in vector search, its contributions will not meet. If different chunks incorrectly share one ID, the merge can combine evidence for different objects. Decide whether the ranked unit is a document, passage or chunk before evaluating the result.

The lab rejects repeated IDs within any individual source list, including repetitions beyond the window. This is a deliberate input policy, not a claim about every search product. It prevents the same result from receiving multiple contributions within one list and makes unexpected upstream duplication visible instead of silently repairing it.

The same ID appearing in different source lists is expected and receives multiple contributions. Repeating an entire retriever list is also accepted by the function and adds another vote. That illustrates a configuration hazard: duplicating a source is an implicit weighting decision, not independent confirmation of relevance.

When exact fused scores tie, the implementation sorts by the document ID string in ascending order. This gives a reproducible fixture result. Do not assume that a vendor’s tie policy is identical, and do not present an arbitrary tie order as evidence that one tied document is more relevant than another.

Run the complete exact-arithmetic Python lab

Save the example as rrf_lab.py and run python rrf_lab.py with Python 3.12. No packages, network requests, credentials or model downloads are needed. The function accepts two or more ordered lists of nonempty string IDs. Empty source lists are valid; duplicate IDs within a list and invalid parameters are rejected.

The exact published script passed 1,523 checks on Python 3.12.14. Its 300 seeded fixtures compare list-first accumulation with a separate document-first rank-map oracle. They also check final ordering, source-list permutation invariance, equivalence to explicitly pre-truncated lists and a score bound. Targeted checks cover the worked scores, empty inputs, ties and repeated-source voting.

Fraction preserves exact arithmetic for this small teaching fixture. It makes equal scores and expected values directly inspectable. This is not a recommendation to replace a search engine’s numeric implementation with arbitrary-precision fractions in a latency-sensitive production path. Benchmark the implementation appropriate to that environment separately.

from fractions import Fraction
import random
import sys

def fuse(rankings, rank_constant=60, window=50):
    # Ordered lists of stable document IDs; scores are intentionally absent.
    if type(rank_constant) is not int or rank_constant < 1:
        raise ValueError('rank_constant must be a positive integer')
    if type(window) is not int or window < 1:
        raise ValueError('window must be a positive integer')
    if not isinstance(rankings, (list, tuple)) or len(rankings) < 2:
        raise ValueError('provide at least two ranked lists')
    scores = {}
    for ranking in rankings:
        if not isinstance(ranking, (list, tuple)):
            raise ValueError('each ranking must be an ordered list or tuple')
        if any(not isinstance(doc, str) or not doc for doc in ranking):
            raise ValueError('document IDs must be nonempty strings')
        # Reject duplicates even beyond the retained window: fixture policy.
        if len(set(ranking)) != len(ranking):
            raise ValueError('duplicate document ID within one ranking')
        for rank, doc in enumerate(ranking[:window], start=1):
            scores[doc] = scores.get(doc, Fraction()) + Fraction(
                1, rank_constant + rank)
    # Explicit fixture tie policy; not a promise about a search engine.
    return sorted(scores.items(), key=lambda row: (-row[1], row[0]))

checks = 0

def check(value):
    global checks
    assert value
    checks += 1

lists = [['A', 'B', 'C'], ['B', 'D', 'A']]
rows = fuse(lists, 60, 3)
check([doc for doc, score in rows] == ['B', 'A', 'D', 'C'])
check(dict(rows)['B'] == Fraction(1, 62) + Fraction(1, 61))
check(dict(rows)['A'] == Fraction(1, 61) + Fraction(1, 63))
check([doc for doc, score in fuse(lists, 60, 1)] == ['A', 'B'])
check(fuse([['B', 'A'], ['A', 'B']]) == [
    ('A', Fraction(1, 61) + Fraction(1, 62)),
    ('B', Fraction(1, 61) + Fraction(1, 62))])
check(fuse([[], []]) == [])
check(fuse([['A'], []]) == [('A', Fraction(1, 61))])
# Repeating a whole source adds another vote; it is not deduplicated.
check(dict(fuse([['A'], ['B'], ['A']]))['A'] == Fraction(2, 61))
check(Fraction(1, 2) / Fraction(1, 3) >
      Fraction(1, 61) / Fraction(1, 62))
for kwargs in [{'rank_constant': 0}, {'rank_constant': True},
               {'rank_constant': 1.5}, {'window': 0},
               {'window': False}, {'window': 1.5}]:
    try:
        fuse(lists, **kwargs)
    except ValueError:
        check(True)
    else:
        raise AssertionError('invalid parameter accepted')
for bad in [[], [['A']], 'AB', [['A'], 'B'], [[''], []],
            [[1], []], [['A', 'A'], []], [['A', 'B', 'B'], []]]:
    try:
        fuse(bad, window=1)
    except ValueError:
        check(True)
    else:
        raise AssertionError('invalid ranking accepted')

rng = random.Random(97)
universe = [f'doc-{n:02}' for n in range(20)]
for _ in range(300):
    rankings = [rng.sample(universe, rng.randrange(21))
                for _ in range(rng.randrange(2, 6))]
    k = rng.choice([1, 5, 20, 60])
    window = rng.randrange(1, 21)
    actual = fuse(rankings, k, window)
    # Independent document-first oracle: derive rank maps, then sum by ID.
    positions = [{doc: index + 1 for index, doc in enumerate(r[:window])}
                 for r in rankings]
    candidates = set().union(*(p.keys() for p in positions))
    expected = {doc: sum((Fraction(1, k + p[doc])
                         for p in positions if doc in p), Fraction())
                for doc in candidates}
    check(dict(actual) == expected)
    check(actual == sorted(expected.items(), key=lambda row: (-row[1], row[0])))
    check(actual == fuse(list(reversed(rankings)), k, window))
    check(actual == fuse([r[:window] for r in rankings], k, window))
    check(all(0 < score <= Fraction(len(rankings), k + 1)
              for doc, score in actual))

for doc, score in rows:
    print(doc, str(score), f'{float(score):.9f}')
print(f'PASS: {checks} checks; 300 seeded fixtures; Python {sys.version.split()[0]}')

A fused score is not a calibrated probability of relevance

In this unweighted function, each list contributes at most 1/(k + 1) to a document. With L lists, the score is therefore bounded above by L/(k + 1). The lab checks that bound. Adding sources can change the score range even before considering whether the new sources help the ranking.

Consequently, a threshold copied from an experiment with two sources may have a different interpretation after introducing a third. Even under the same source count, a score reflects the supplied ranks and candidate windows. It does not mean “this result has a 90 percent chance of being correct.”

RRF also discards raw score gaps. Two source lists with identical order but very different confidence patterns give this implementation the same contributions. That can be useful when score scales are hard to combine, but it is a tradeoff to evaluate. If calibrated magnitudes matter for your task, compare an appropriate alternative instead of assuming rank-only fusion preserves that information.

Evaluate the merge as a retrieval change, not an answer-quality claim

Preserve the same query set, corpus version, identity unit and relevance labels when comparing a baseline with a fused ranking. Save each source list as well as the fused output. That lets you distinguish a candidate-recall limitation from an ordering change and reproduce why a particular document moved.

Inspect representative failure cases rather than relying only on an aggregate metric. An exact identifier lookup may behave differently from a paraphrased conceptual question. A query containing a rare product code may need a different diagnostic explanation from one with ambiguous terminology. Use actual labeled examples to decide what changed; do not infer quality from a higher fused score.

Keep reranking and answer generation as separate stages in the analysis. Fusion can supply candidates to a later reranker, and a generator may still omit or misuse a retrieved source. A good retrieval metric does not prove a cited answer is supported. The existing metrics guide and free retrieval-metrics calculator can help compare labeled rankings without conflating these stages.

Carry the local contract into the engine integration carefully

Before mapping this function to a product API, check that product’s current candidate-window behavior, rank-constant options, weighting support, filters and tie handling. The example is an unweighted finite-list merge. It is not an Elasticsearch or Azure request template and does not claim to reproduce every detail of either service.

Keep access filtering and the selected corpus consistent across the input results. Merging already-returned IDs does not itself establish permission to retrieve a document or expose its content. If a candidate’s identity cannot be resolved to the same authorized object in the next stage, treat that as a pipeline defect rather than a score adjustment.

A useful implementation record includes the source names, their ordered IDs, window limits, rank constant, duplicate policy, tie rule and final output budget. Those details make the merged ranking explainable. Once the arithmetic is correct, use controlled relevance evaluation to decide whether the fusion is useful for the reader’s actual search task.

KEEP THESE THREE THINGS

Your next steps

  1. Fuse stable document identities and ranked positions, not uncalibrated raw score magnitudes.
  2. Keep the rank constant, per-source candidate window and final result count separate.
  3. Specify duplicate and tie policies so a result can be reproduced and inspected.
  4. Test arithmetic independently, then evaluate retrieval quality with fixed queries and relevance labels.

Sources & official resources

Linked resources checked on 2026-11-05. Technical behavior and provider guidance can change; check the documentation for the version you use.

About this guide and its recommendations

Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.

Suggest a correction →