Hybrid search: fuse two rankings with RRF
BM25 and embeddings give scores that cannot be compared. Reciprocal rank fusion ignores them and uses only the positions.
LEXICAL is the list of ids BM25 returned for a query, best first, and DENSE the one the embedding search returned. A BM25 score of 4.5 and a cosine of 0.71 cannot be added. Positions can.
Write rrf(rankings, k): it takes an array of id lists and returns [{ id, score }], where
score(id) = sum, over each list that contains it, of 1 / (k + position)
with the position starting at 1. Rules:
kisK(60) when not given;- an id repeated inside one list counts once, at its first position, and the later copies take no place;
- sort by
score, highest first, and on a tie byidin alphabetical order; - do not modify the input lists.
fuseTop(rankings, n, k) is already written on top of rrf and returns the first n ids.
Challenges 0/6
- What appears in both lists beats the top of a single one
- The score is the sum of 1 / (k + position)
- Returns every id, with ties in alphabetical order
- k decides how much being at the top counts
- An id repeated in one list counts once and takes no place
- With no lists returns [] and leaves the input alone
function rrf(rankings, k = K) {
// score(id) = sum over the lists of 1 / (k + position), position starting at 1
// an id repeated inside one list counts once, at its first position
// return [{ id, score }], highest score first; ties by id
return (rankings[0] || []).map((id) => ({ id, score: 0 }));
}
function fuseTop(rankings, n, k = K) {
return rrf(rankings, k).slice(0, n).map((r) => r.id);
}
console.log(rrf([LEXICAL, DENSE]).slice(0, 3));Tab indents, Ctrl+Z undoes. To leave the editor with the keyboard: Esc, then Tab.
Why this matters
A RAG with a single retriever has a blind spot: the lexical one does not understand synonyms and the semantic one gets lost with codes and names. The usual answer is to run both and fuse, and RRF is the fusion that ships in Qdrant, Elasticsearch and OpenSearch because it needs no calibration: it only looks at positions. The constant k stops a first place in one list from flattening a document both lists consider good. The next step, reordering the fused candidates with a reranker, is measured in local RAG with Qdrant and bge-m3.
Go deeper: the related guide →
This in production, with your data? Let's talk for 15 minutes →