Hybrid search and reranking
9 min read
Two searches, two kinds of miss
The last two Lessons gave you two ways to search, and each fails where the other works.
- BM25A keyword scoring formula that ranks passages by the words they share with a query. A rare word counts for more than a common one, and a long passage is not rewarded just for being long. finds the exact product code
XR-500, and it misses a question that says "money back" when the document says "refund". - Semantic search finds the refund passage, and it can rank a passage about a different bike above the one with the right code.
Running both and merging the results is called Hybrid searchRetrieval that runs a keyword search and a vector search, then merges the two ranked lists. It finds exact names and also passages that use different words for the same idea.. It is the most common design in production RAG systems, because each search covers the other's weakness.
Merging two rankings
The two searches score passages on different scales. A BM25 score can be 12.4 and a cosine score can be 0.81, and adding them makes no sense. The usual fix ignores the scores and uses only the rank.
Reciprocal rank fusion, or RRF, gives each passage 1 / (k + rank) points from every list it appears in, and adds them up. The constant k, usually 60, stops the first place from dominating. A passage ranked well by both searches collects two good contributions and rises. This method needs no tuning of scales, which is why it is popular. It comes from a 2009 paper by Cormack and colleagues.
Reordering with a reranker
Fusion is quick, but it still judges each passage alone. A RerankingA second pass that scores the top results of a first search more carefully and reorders them. It is slower than the first search, so it runs only on a short list. is a second model that reads the question and one passage together and scores how well that passage answers that question. Reading both at once lets it notice things neither search could, such as the question asking about returns while the passage covers battery warranty. This kind of model is often called a cross-encoder.
The cost is speed. A reranker must run once for every passage, so you cannot run it on the whole collection. You run it only on the shortlist, perhaps 20 to 50 passages, and keep the top few.
- Search twiceKeyword and semantic search each return their top 20 to 50.
- FuseMerge the two lists into one shortlist with RRF.
- RerankA reranker scores each shortlisted passage against the question.
- Keep a fewSend the top 3 to 5 passages to the model.
Both steps in code
The program below runs fusion and then a reranking pass. The real reranker would be a trained model. Here, read_together is a stand-in that counts words the question and passage share in the same order, so it looks at the pair together, which is the property that matters.
from difflib import SequenceMatcher
passages = {
"returns": "Return an unused XR-500 bike within 30 days for a refund.",
"refund-guide": "Refunds are paid to your original payment method.",
"xr-500-manual": "The XR-500 has a 500 watt motor and a 36 volt battery.",
"warranty": "The XR-500 battery has a 2 year warranty.",
"shipping": "Standard shipping takes 3 to 5 business days.",
}
def fuse(*rankings, k=60):
scores = {}
for ranking in rankings:
for position, name in enumerate(ranking, start=1):
scores[name] = scores.get(name, 0) + 1 / (k + position)
return sorted(scores, key=lambda name: -scores[name])
keyword = ["xr-500-manual", "warranty", "returns", "shipping"]
semantic = ["refund-guide", "warranty", "returns", "xr-500-manual"]
shortlist = fuse(keyword, semantic)
print("after fusion: ", shortlist)
def read_together(question, passage):
a, b = question.lower().split(), passage.lower().replace(".", "").split()
return sum(block.size for block in SequenceMatcher(None, a, b).get_matching_blocks())
question = "can i return my xr-500 for a refund"
reranked = sorted(shortlist, key=lambda name: -read_together(question, passages[name]))
print("after rerank: ", reranked)
print("sent to model: ", reranked[:2])It prints:
after fusion: ['warranty', 'xr-500-manual', 'returns', 'refund-guide', 'shipping']
after rerank: ['returns', 'warranty', 'xr-500-manual', 'refund-guide', 'shipping']
sent to model: ['returns', 'warranty']The warranty passage is in the middle of both lists, so fusion puts it first. Both searches half-liked it, and neither loved it. The reranker reads the question next to each passage, finds that returns shares the words "return", "xr-500" and "refund" in the right order, and moves it to the top. Only the top two go to the model.
This is the typical pattern: fusion makes sure the right passage is on the shortlist, and the reranker makes sure it comes first.
When to add each step
| Hybrid search | Reranking | |
|---|---|---|
| Fixes | Exact terms missed by meaning search, and meaning missed by keywords | A shortlist in the wrong order |
| Extra cost | A second search, which is cheap | A model run for each shortlisted passage |
| Adds delay | A little | Noticeable, so keep the shortlist short |
| Add it when | Questions mix codes, names and plain language | The right passage is on the list but not first |
Add them in that order, and only when your test questions show the need. The Lesson Measuring retrieval quality gives the numbers to check. Reranking models are available as open models that you run yourself, for example through the Sentence Transformers library, and as hosted services.
Why combine keyword and vector search?
A user types the code 'XR-500' in one query and 'money back' in another.
Keyword search suits exact names, vector search suits different wording.
What does reciprocal rank fusion do?
Two ranked lists use scores on different scales.
Scores from different systems are not comparable, but positions are.
Why rerank only a short list?
A reranker reads the question and each passage together.
A cheap first search narrows the field and the reranker orders the survivors with more care.
Your reading position is saved
0 of 15 complete
Lesson complete
Hybrid search and reranking
Up next