Run lexical and vector retrieval over the same permitted revision set, then fuse ranks without pretending their raw scores are comparable.
Hybrid retrieval: fuse exact terms and semantic candidates by rank
Keep both candidate paths honest
A user may ask for a named status code and its meaning in different words. Keyword search protects exact strings, version tags and identifiers; dense retrieval helps with paraphrases. Each leg must apply the same tenant, document-state and revision constraints before its results reach fusion. If one leg indexes stale policy or ignores a revocation, its high rank cannot be made safe by later scoring. Filtered ANN tests the semantic leg independently.
Fuse ranks, then inspect the result
Reciprocal rank fusion awards a candidate one divided by a rank constant plus its position in each list. A passage appearing in both lists receives contributions from both. This avoids adding an unbounded keyword score to a cosine similarity on a different scale. It discards score margins, so a clear lexical winner and a weak lexical hit can be treated as neighboring ranks. Compare fusion against each leg on judged questions, particularly exact-ID queries.
Preserve identity while deduplicating
The key is a stable passage identity tied to document revision, not only display text. Two copied sections from different policies may have identical wording but different owners or effective dates. Deduplicate the same passage returned by both legs, then group near-duplicates for context selection rather than erasing provenance. Evidence packing decides how many passages from one document belong in the prompt.
Tune the window, not the formula alone
Each leg contributes only the candidates it retrieved. A fusion constant cannot recover a passage absent from both top-K lists. Measure candidate recall while changing lexical depth, vector depth and fusion constant; track p95 latency and reranker input size. If exact identifiers are mandatory, apply a hard exact-match gate before or after fusion according to the query contract, not an arbitrary score threshold on the fused rank.
Worked contract
from collections import defaultdict
def reciprocal_rank_fusion(lexical: list[str], semantic: list[str],
rank_constant: int = 37) -> list[str]:
if rank_constant < 1:
raise ValueError("rank constant must be positive")
scores = defaultdict(float)
for ranking in (lexical, semantic):
for position, passage_id in enumerate(dict.fromkeys(ranking), start=1):
scores[passage_id] += 1 / (rank_constant + position)
return sorted(scores, key=lambda passage_id: (-scores[passage_id], passage_id))
keyword_hits = ["policy-r8-ax47", "policy-r8-refunds", "guide-r3"]
vector_hits = ["policy-r8-refunds", "policy-r8-ax47", "manual-r6"]
ranking = reciprocal_rank_fusion(keyword_hits, vector_hits)
assert ranking[:2] == ["policy-r8-ax47", "policy-r8-refunds"]
assert len(ranking) == 4Performance and operating cost
Fusion scans L + V ranked candidates and stores at most their union, so expected O(L + V) score work and O(U) memory, followed by O(U log U) sorting. It adds almost no model cost, while running two retrieval legs may double search traffic. Bound both depths and measure whether extra recall justifies their latency.
Common Mistakes
- Adding raw keyword and vector scores without a tested normalization rule.
- Fusing candidates from different permission or index generations.
- Deduplicating by text and losing document ownership or revision.
- Tuning the fusion constant while the needed passage never enters either list.
Validation drill
Judge 63 queries split across exact identifiers, paraphrases and mixed language. Compare keyword-only, vector-only and fused recall at 12; record the extra latency and every newly missed exact-token query.
Read next
- Retrieval query routing: preserve exact constraints before search
- Reranking: spend model budget on a bounded candidate window
- Context packing: retain independent evidence under a token cap
- Retrieval design: compare lexical, semantic and reranked candidates
