Hybrid Search and Reranking
Hybrid search combines keyword search, which matches the exact words of a question, with vector search, which matches meaning, so that each covers the other's blind spots. A reranker then reads the question together with each of the top candidates and reorders them more accurately than either first-stage search can. These are the standard building blocks of retrieval in production RAG systems, and they are only useful if you measure whether the right document is being found.
The Pieces
| Piece | Description |
|---|---|
| Keyword search (BM25) | It is used to score documents by shared words, weighting rare words more; strong for names, codes and exact terms |
| Vector search | Embeddings and cosine similarity from "Similarity and Cosine Distance"; strong for reworded questions |
| Hybrid fusion | It is used to merge two rankings; reciprocal rank fusion (RRF) adds 1 / (60 + rank) from each list |
| Reranker (cross-encoder) | A model that reads the question and a candidate together and scores how well they match; slower but more accurate |
| Metadata filters | It is used to restrict results by date, type or permission before ranking |
| Recall@k | The share of questions whose right document is in the top k results |
| MRR | Mean reciprocal rank: 1 for first place, 1/2 for second, 1/3 for third, averaged |
Example: Four Retrieval Methods, Measured
The programs need pip install sentence-transformers numpy, faq.json from "Semantic Search" and eval_set.json from "Building an Evaluation Set". Download and loading messages are left out of the output shown.
This program runs the 40 answerable questions from Campus Helper's evaluation set through four methods, and checks where the FAQ entry containing the expected answer lands.
import json
import math
import re
from collections import Counter
import numpy as np
from sentence_transformers import CrossEncoder, SentenceTransformer
texts = [item["text"] for item in json.load(open("faq.json"))] # from "Semantic Search"
cases = [c for c in json.load(open("eval_set.json")) if c["must_contain"]] # the 40 answerable questions
relevant = [{i for i, t in enumerate(texts) if c["must_contain"] in t} for c in cases]
# 1. Keyword search: BM25, the classic lexical ranking formula
def words(s):
return re.findall(r"[a-z0-9$]+", s.lower())
docs = [words(t) for t in texts]
avg_len = sum(map(len, docs)) / len(docs)
df = Counter(w for d in docs for w in set(d))
def bm25(query, k1=1.5, b=0.75):
scores = []
for d in docs:
tf, s = Counter(d), 0.0
for w in words(query):
if w in tf:
idf = math.log(1 + (len(docs) - df[w] + 0.5) / (df[w] + 0.5))
s += idf * tf[w] * (k1 + 1) / (tf[w] + k1 * (1 - b + b * len(d) / avg_len))
scores.append(s)
return list(np.argsort(scores)[::-1])
# 2. Vector search: embeddings and cosine similarity
model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
vectors = model.encode(texts, normalize_embeddings=True)
def dense(query):
return list(np.argsort(vectors @ model.encode(query, normalize_embeddings=True))[::-1])
# 3. Hybrid: reciprocal rank fusion of the two rankings
def hybrid(query, k=60):
score = Counter()
for ranking in (bm25(query), dense(query)):
for rank, i in enumerate(ranking):
score[i] += 1 / (k + rank + 1)
return [i for i, _ in score.most_common()]
# 4. Rerank: a cross-encoder reads the question and each of the top 10 candidates together
reranker = CrossEncoder("cross-encoder/ms-marco-MiniLM-L6-v2")
def reranked(query):
candidates = hybrid(query)[:10]
scores = reranker.predict([(query, texts[i]) for i in candidates])
return [candidates[j] for j in np.argsort(scores)[::-1]]
print(f"{len(cases)} questions, {len(texts)} FAQ entries\n")
print(f"{'method':22}{'Recall@1':>9}{'Recall@3':>9}{'MRR':>7}")
for name, search in [("keyword (BM25)", bm25), ("vector", dense), ("hybrid (RRF)", hybrid), ("hybrid + reranker", reranked)]:
r1 = r3 = mrr = 0
for c, rel in zip(cases, relevant):
ranking = search(c["question"])
r1 += bool(rel & set(ranking[:1]))
r3 += bool(rel & set(ranking[:3]))
first = next((pos for pos, i in enumerate(ranking) if i in rel), None)
mrr += 1 / (first + 1) if first is not None else 0
n = len(cases)
print(f"{name:22}{r1 / n:9.1%}{r3 / n:9.1%}{mrr / n:7.3f}")
q = "Can we visit the campus before applying?"
print(f"\n'{q}'")
for name, search in [("keyword", bm25), ("vector", dense), ("reranked", reranked)]:
print(f" {name:9} top result: {texts[search(q)[0]]}")40 questions, 50 FAQ entries
method Recall@1 Recall@3 MRR
keyword (BM25) 60.0% 82.5% 0.714
vector 90.0% 97.5% 0.936
hybrid (RRF) 80.0% 90.0% 0.862
hybrid + reranker 92.5% 100.0% 0.958
'Can we visit the campus before applying?'
keyword top result: Families can book a campus tour on Tuesdays and Thursdays.
vector top result: International students need a valid student visa before enrollment.
reranked top result: International students need a valid student visa before enrollment.Explanation:
| Method | Recall@1 | Recall@3 | MRR |
|---|---|---|---|
| Keyword (BM25) | 60.0% | 82.5% | 0.714 |
| Vector | 90.0% | 97.5% | 0.936 |
| Hybrid (RRF) | 80.0% | 90.0% | 0.862 |
| Hybrid + reranker | 92.5% | 100.0% | 0.958 |
- BM25 is written out in full: each shared word adds a score that is higher for rare words (
idf) and for repeated words, with a penalty for long documents. It struggles with reworded questions: "shot records" doesn't share words with "vaccination records". - Vector search is much stronger on these reworded parent questions.
- Hybrid fusion scored lower than vector search alone here. Fusion gives both lists equal say, and BM25's mistakes pulled good results down. On collections full of product codes, names or exact terms, the result is often the other way round, which is why you measure rather than assume.
- The reranker reads each question with its top 10 candidates and gives the best results: every right answer in the top 3. Its cost is time: it runs a model for every candidate.
- The example question shows the trade-off: "visit the campus" matches the tour entry by keyword, while meaning-based methods are fooled by "visa". No single method is right every time.
Choosing a Retrieval Setup
| Situation | Good starting point |
|---|---|
| Reworded natural-language questions | Vector search, then a reranker |
| Codes, names, exact phrases | Keyword search, or hybrid |
| Mixed content | Hybrid with tuned weights, then a reranker |
| Private or role-based documents | Metadata and permission filters before ranking; see "Advanced RAG Patterns" |
| Tight latency budget | Rerank fewer candidates, or a smaller reranker |
Common Mistakes
Judging retrieval by the final answer only. Measure retrieval separately, or you can't tell which stage failed.
Adding hybrid search because it's popular. Here it made results worse until a reranker was added.
Reranking too few candidates. If the right document isn't in the first-stage list, no reranker can find it.
Forgetting filters. Permissions and dates must be applied before ranking.
Interview Corner
What is hybrid search, and when does it help?
Combining keyword (lexical) and vector (semantic) retrieval, usually by fusing their rankings. It helps when queries mix exact terms, such as codes and names, with natural language. Measure it: on reworded questions, vector search alone can be better.
What does a reranker do?
It reads the query and each candidate together, usually with a cross-encoder, and reorders a short list from a fast first-stage search. It improves precision at the top at the cost of extra latency.
Practice
Exercise: weight the fusion. Change hybrid() so the vector ranking counts twice as much as BM25 (add 2 / (k + rank + 1) for it). Do Recall@1 and MRR improve over plain vector search?
Check your understanding:
- Why did BM25 miss many reworded questions?
- Why did hybrid fusion score lower than vector search here?
- What is the MRR of a question whose right answer is in third place?
Key Takeaways
Quick reference
| Need | Code or formula |
|---|---|
| BM25 term score | idf × tf × (k1 + 1) / (tf + k1 × (1 - b + b × len / avg_len)) |
| Reciprocal rank fusion | score += 1 / (60 + rank + 1) from each list |
| Reranker | CrossEncoder("cross-encoder/ms-marco-MiniLM-L6-v2").predict(pairs) |
| Recall@k | right document in ranking[:k] |
| MRR | average of 1 / position of the first right document |
Was this tutorial helpful?