How to Evaluate Hybrid Search and Reranking for RAG
Guides

How to Evaluate Hybrid Search and Reranking for RAG

Build a reproducible RAG retrieval evaluation with relevance labels, reciprocal rank fusion, reranking, query-level metrics and latency checks.

By Daniel Mercer 10 mins read
Published: Updated:

Reliable RAG evaluation separates candidate recall, ranking quality and answer support while tracking latency, permissions and reproducible traces. Photo: Hansheng Zhao / Unsplash 

Build a reproducible RAG retrieval evaluation with relevance labels, reciprocal rank fusion, reranking, query-level metrics and latency checks.

A retrieval-augmented generation system can produce a fluent answer from the wrong evidence. Before changing the language model or adding more elaborate prompts, check whether search returns the documents needed to answer the question. Hybrid search and reranking can help, but they add value only when a controlled evaluation shows where they improve retrieval and what they cost.

This advanced guide assumes familiarity with embeddings and the basic RAG workflow. You will build a small evaluation design, implement reciprocal rank fusion in Python and measure ranking quality without confusing an illustrative example with a real benchmark. The code uses only the Python standard library; production indexing and model hosting remain separate implementation choices.

Freeze the Evaluation Unit Before Comparing Systems

Start with a versioned corpus and stable document identifiers. Record which source version each searchable chunk came from, including its access policy and effective date where relevant. A search result is difficult to evaluate if the document changes between runs or several chunks silently point to outdated copies.

Choose whether relevance is judged at the chunk or source-document level. A question may require two passages from the same document, while another needs evidence from several sources. Counting three overlapping chunks as three independent relevant documents can inflate recall without improving the answer.

Create a query set that represents actual information needs. Include exact identifiers, natural-language descriptions, ambiguous questions, multi-source questions and questions the corpus cannot answer. Keep development queries for tuning and a separate held-out set for the final comparison.

For each answerable query, record the relevant IDs and the evidence supporting that judgment. Graded labels can distinguish essential passages from background context, but they require a clearly documented rubric. Review disagreements rather than accepting a model-generated relevance label as unquestioned ground truth.

Compare Lexical and Dense Retrieval Separately

Lexical search is useful when exact terms, product codes or uncommon names matter. Dense retrieval compares learned representations and can find related wording that shares few literal terms with the question. Neither approach reliably dominates every query type.

The BEIR paper evaluates retrieval across varied datasets and illustrates why generalization matters. For an internal knowledge system, your corpus and query distribution still determine the useful comparison. A benchmark result from another domain does not establish that a retriever will preserve your exact policy identifiers or distinguish current from superseded instructions.

Run both methods independently before combining them. Save their ranked candidate lists, retrieval times, index versions and configurations. If dense retrieval misses exact codes while lexical search handles them well, that diagnosis is more useful than an unexplained improvement in a single aggregate score.

Apply trusted access restrictions before unauthorized content reaches a reranker, answer generator or user-visible trace. Filtering only the final answer is too late. Keep the candidate-generation and permission logic consistent across systems so an apparent quality gain does not come from searching a broader unauthorized corpus.

Fuse Ranks Without Mixing Incompatible Scores

Raw lexical and embedding scores often have different scales and meanings. Adding them together can make one method dominate for accidental numerical reasons. Reciprocal rank fusion, or RRF, combines list positions instead of assuming that raw scores are directly comparable.

The original paper describes the method, and the Elasticsearch reference documents a concrete implementation. In its basic form, each document receives a contribution of one divided by a rank constant plus its position in each list. Positions start at one, and contributions are summed across lists containing that document.

The rank constant controls how strongly the method favors the very top positions. Candidate-window sizes also matter because a document cannot contribute from a list that did not retrieve it. Treat both as settings to evaluate, rather than copying a default and calling it optimal.

The following complete example uses invented rankings and relevance judgments. Save it as evaluate_retrieval.py and run it with Python 3. It does not contact a search service or generate model embeddings.

def reciprocal_rank_fusion(rankings, rank_constant=60):
    if rank_constant < 0:
        raise ValueError("rank_constant must be nonnegative")
    scores = {}
    for ranking in rankings:
        unique = list(dict.fromkeys(ranking))
        for rank, doc_id in enumerate(unique, start=1):
            scores[doc_id] = scores.get(doc_id, 0.0) + 1 / (rank_constant + rank)
    return sorted(scores, key=lambda doc_id: (-scores[doc_id], doc_id))
def query_metrics(ranked, relevant, k):
    if k <= 0 or not relevant:
        raise ValueError("Use positive k and a query with known relevant documents")
    top = list(dict.fromkeys(ranked))[:k]
    recall = len(set(top) & relevant) / len(relevant)
    rr = next((1 / rank for rank, doc_id in enumerate(top, 1)
               if doc_id in relevant), 0.0)
    return recall, rr
if __name__ == "__main__":
    lexical = ["a", "c", "b"]
    dense = ["b", "a", "d"]
    fused = reciprocal_rank_fusion([lexical, dense])
    recall, rr = query_metrics(fused, {"b", "d"}, k=3)
    print("Fused ranking:", fused)
    print(f"Recall@3: {recall:.2f}")
    print(f"Reciprocal rank@3: {rr:.2f}")

The fused order is a, b, c, d. With b and d marked relevant, the top three retrieve one of two relevant documents, producing recall@3 of 0.50. The first relevant result is in position two, so this query’s reciprocal rank@3 is also 0.50.

The implementation removes duplicate IDs within each input ranking before assigning positions and uses the ID to break score ties deterministically. This convention should match your evaluation pipeline. If distinct chunks are your evaluation unit, use distinct chunk IDs and map them to parent documents explicitly rather than collapsing unrelated passages by accident.

Add Reranking After Candidate Recall Is Adequate

A reranker examines query-document pairs and produces a new ordering of a limited candidate set. The retrieve-rerank guide explains the common pattern of inexpensive first-stage retrieval followed by more expensive pairwise scoring. A cross-encoder can use joint information about the question and passage that independent embedding similarity does not capture.

A reranker cannot recover an essential passage absent from its candidate set. Measure candidate recall before spending time tuning the final ordering. Expanding the union of lexical and dense candidates may help, but it increases processing cost and can add irrelevant material.

Set a clear maximum number of candidates and an input-length policy. Long documents may be truncated, and the relevant sentence can disappear if it sits beyond the model’s limit. Chunking strategy, title inclusion and the amount of surrounding context are part of the configuration you are evaluating.

Do not interpret arbitrary reranker scores as calibrated probabilities. The cross-encoder documentation explains that some models return logits or other scores rather than values constrained to zero through one. Applying a sigmoid changes the scale; it does not by itself establish that a score of 0.8 means an 80% chance of relevance.

Use Metrics That Match the Failure You Care About

Recall@k measures the fraction of known relevant items present in the top k results. It is useful when missing an essential source is costly. Its denominator is only as good as the relevance judgments, so incomplete labels can make genuinely useful additional results look like errors.

Reciprocal rank measures how early the first relevant result appears. Mean reciprocal rank averages that quantity across queries. Report the cutoff explicitly, and do not call the single-query number in the Python example MRR.

For graded relevance, normalized discounted cumulative gain can account for both relevance level and position. Before using it, define the gain mapping and cutoff consistently. Changing the rubric or treating redundant chunks as independent evidence can change the score without changing the user experience.

Evaluate unanswerable questions separately. The example function rejects an empty relevant set because recall would have a zero denominator. Do not silently drop such queries from the product assessment: measure whether the system abstains, returns a plausible distraction or claims that missing information exists.

For multi-source questions, inspect whether the retrieved evidence supports all required parts. A first relevant hit can produce a good reciprocal rank while leaving half the question unsupported. Pair aggregate metrics with an error taxonomy and representative failed queries.

Run an Ablation With Fixed Conditions

Compare lexical retrieval, dense retrieval, fused retrieval and fused retrieval followed by reranking. Use the same corpus snapshot, query set, access rules and relevance judgments. Keep candidate and final-result cutoffs visible so the comparison does not hide a much larger search budget in one configuration.

Tune on development queries, then run the chosen configurations on the held-out set once the decision rules are fixed. Record per-query metrics, not just averages. This lets you inspect whether a gain comes from broad improvements or a handful of unusually easy queries.

If the sample is large enough, a paired analysis of query-level differences can help quantify uncertainty. Preserve the same queries in each paired comparison, and explain how intervals were calculated. Do not manufacture statistical confidence from a few handpicked examples or treat correlated paraphrases as independent tasks.

Retain an honest baseline. A simple lexical system may already solve exact-code questions cheaply, while a dense system may help on paraphrases. The purpose of the experiment is to choose a configuration for a particular workload, including the possibility that an additional component does not earn its cost.

Measure Latency, Cost and Answer Quality Separately

Measure end-to-end search latency as well as each stage. Include candidate retrieval, network calls, reranking and permission checks. Record whether caches are warm, which hardware or hosted service is used and how many candidates are processed.

Report the sample size and the percentile calculation behind p50 or p95 latency. A high-percentile estimate from a tiny sample is unstable. Compare repeated representative runs and distinguish steady-state measurements from a cold deployment starting its first model instance.

Track cost per completed information task, including failures and retries, rather than only the price of one reranker call. A configuration that slightly improves ranking but routinely exceeds the application’s deadline may be a poor choice for an interactive assistant.

Finally, evaluate the generated answer in a separate layer. Check whether claims are supported by the retrieved passages, whether citations point to the right source and whether the system handles contradictory evidence. Better retrieval can make a correct answer possible without guaranteeing that the generator uses it correctly.

Keep a Reproducible Retrieval Trace

Save a trace containing the query ID, corpus version, access-policy version, retriever settings, candidate IDs, fused order, reranker version, final order and stage timings. Store only information permitted by your logging policy, and restrict traces that reveal private document titles or content.

Keep raw source material separate from trusted instructions. A retrieved page can contain commands aimed at the agent; our prompt injection guide explains why search relevance does not establish authority. Ranking a passage highly should never grant it permission to change tool access or override the user’s task.

Before rollout, set regression thresholds for important query groups and preserve the previous working configuration. Re-run the evaluation when chunking, indexes, embedding models or rerankers change. Those changes can affect retrieval even when the answer-generation prompt remains identical.

A practical release decision combines evidence coverage, ranking quality, latency and operational cost. Use the traces to explain which queries improved and which regressed. That gives the next iteration a specific problem to solve instead of another unmeasured layer in the RAG pipeline.

Disclaimer: AIstify is an independent media brand owned and operated by NuvexMedia LLC, publishing news, research, and insights on artificial intelligence, emerging technologies, automation, and related industries. NuvexMedia LLC invests in and collaborates with companies across the AI, technology, software, and digital innovation sectors. These relationships do not influence AIstify’s editorial coverage, and the publication maintains full editorial independence to provide accurate, timely, and objective information. © 2026 NuvexMedia LLC. All rights reserved. This content is for informational purposes only and should not be considered legal, tax, investment, financial, or other professional advice.