LESSON 49 Β· RETRIEVAL

Reranking

Learn how a reranker takes an initial set of retrieved documents and puts the most relevant results first.

30 min readβ€’Intermediateβ€’Generative AI

By the end of this lesson, you will be able to:

  • Explain what reranking means in a retrieval pipeline.
  • Understand first-stage retrieval and second-stage reranking.
  • Compare bi-encoder retrieval with cross-encoder reranking.
  • Understand candidate sets, rerank-K, and final Top-K.
  • Build simple Python reranking examples.
  • Understand latency and cost trade-offs.
  • Evaluate whether reranking improves RAG retrieval quality.
1

What Is Reranking?

Reranking is a second-stage retrieval step. A fast retriever first finds a larger set of candidates. A more precise model then scores those candidates again and changes their order.

Simple idea:Retrieve broadly first, then examine the best candidates more carefully and move the most relevant ones to the top.
EXAMPLE 1Support question

A vector search returns 20 help articles. A reranker moves the article that directly answers the user's question from position 8 to position 1.

EXAMPLE 2Technical search

A query mentions an API name and a specific error. The reranker favors the document that matches the complete query context.

2

Why Do We Need Reranking?

Initial vector retrieval is designed to be fast over a large collection. The highest-scoring candidates are useful, but their ordering is not always perfect.

First-stage retrieval
  • Very fast
  • Searches many documents
  • Optimized for candidate recall
Reranking
  • More detailed relevance judgment
  • Runs on fewer candidates
  • Optimized for final ordering
3

Two-Stage Retrieval Pipeline

User queryβ€œHow do I reset my API key?”
β†’
RetrieveFind 50 candidates
β†’
RerankScore query + candidate
β†’
Top-KKeep best 5

This design balances speed and relevance: retrieval narrows the search space, while reranking spends more computation only where it matters.

4

Bi-Encoder vs Cross-Encoder

FIRST STAGE

Bi-encoder

The query and documents are embedded separately. Their vectors can be searched efficiently.

SECOND STAGE

Cross-encoder

The query and candidate document are considered together to produce a relevance score.

ADVANTAGE

Speed

Bi-encoders are practical for large collections because document embeddings can be prepared in advance.

ADVANTAGE

Precision

Cross-encoders can inspect interactions between query and document text more directly.

5

What Does a Reranker Actually Score?

A reranker receives a query and a candidate document. It produces a relevance score used to reorder the candidate list.

QUERY

User question

β€œCan I change my billing address after an order?”

+
CANDIDATE

Document chunk

β€œBilling addresses can be changed from the order settings page before shipment.”

The important point is that the reranker evaluates the relationship between the query and each candidate, rather than relying only on precomputed vector distance.

6

Candidate Set: Retrieve More, Rerank Fewer

You normally do not rerank an entire database. Instead, retrieve a manageable candidate set such as 20, 50, or 100 results and rerank those candidates.

Key trade-off:A larger candidate set can improve the chance of finding the right document, but reranking more candidates increases latency and compute cost.
7

Rerank-K vs Final Top-K

Retrieve-K100 candidates
β†’
Rerank-KScore those 100
β†’
Final Top-KReturn best 5

Retrieve-K is the broad candidate count. Final Top-K is what you finally pass to the next stage, such as an LLM.

8

Simple Python Reranking Example

The following example uses a small manual relevance function to demonstrate the idea. Real applications usually use a trained reranker model.

</> Python
query = "reset my API key"
candidates = [
    "How to reset your API key",
    "How to update your billing address",
    "API rate limits and quotas",
]

def simple_score(query, document):
    query_words = set(query.lower().split())
    document_words = set(document.lower().split())
    return len(query_words & document_words)

ranked = sorted(
    candidates,
    key=lambda doc: simple_score(query, doc),
    reverse=True,
)

for document in ranked:
    print(simple_score(query, document), document)

This is only a teaching model. A production reranker learns richer relevance patterns than word overlap.

9

Using a Cross-Encoder in Python

A common teaching example is a cross-encoder that scores query-document pairs together.

</> Python
from sentence_transformers import CrossEncoder

model = CrossEncoder("cross-encoder/ms-marco-MiniLM-L-6-v2")

query = "How do I reset my API key?"
documents = [
    "Reset your API key from the developer settings page.",
    "You can update your billing address from your account.",
    "API requests are limited by your account quota.",
]

pairs = [(query, document) for document in documents]
scores = model.predict(pairs)

ranked = sorted(
    zip(scores, documents),
    key=lambda item: item[0],
    reverse=True,
)

for score, document in ranked:
    print(round(float(score), 3), document)

The model name above is an example for learning. In production, choose and evaluate a reranker that fits your language, domain, quality, latency, and licensing requirements.

10

Reranking in a RAG Pipeline

1. QueryUser asks a question
β†’
2. RetrieveFind 50 candidates
β†’
3. RerankScore candidates
β†’
4. GenerateLLM uses Top-K context

Reranking can improve the context sent to the LLM by pushing highly relevant chunks toward the top and removing weaker candidates before generation.

11

Reranking and Metadata Filtering

Metadata filterregion = US
β†’
RetrieveAllowed candidates
β†’
RerankBest relevance
β†’
Top-KFinal context

Hard constraints such as region, product, language, or access permissions should normally be enforced rather than asking a reranker to ignore invalid documents.

12

Latency and Cost

01More candidates

Reranking 100 documents usually costs more than reranking 20.

02Longer documents

More text can increase model computation.

03Model choice

Larger rerankers can improve quality but may add latency.

04Parallel scoring

Batching candidate pairs can improve throughput.

05Cache wisely

Repeated queries or stable results may benefit from caching.

06Measure end-to-end

Retrieval quality is not useful if the user experience becomes too slow.

13

When Reranking Helps Most

01Close candidates

Several documents are semantically similar and need finer ordering.

02Long queries

The relationship between many query terms can matter.

03Technical content

Precise terminology and context can be important.

04Enterprise search

Many candidates may look relevant at the embedding level.

05RAG

Better context ordering can improve grounded answer quality.

06Search quality

Evaluation shows useful documents are retrieved but ranked too low.

14

When Reranking May Not Be Worth It

Keep retrieval simple
  • The collection is small
  • Initial retrieval is already strong
  • Latency is extremely sensitive
Test reranking
  • Relevant results appear too low
  • Many candidates are near-duplicates
  • Quality gains justify extra compute

Do not add a reranker because it sounds advanced. Add it when an evaluation set shows a measurable benefit.

15

Common Reranking Mistakes

01Reranking too many

Scoring thousands of candidates defeats the purpose of a two-stage pipeline.

02Filtering too late

Invalid or unauthorized documents should not be rescued by relevance scoring.

03Using the wrong model

A general model may not perform well on specialized terminology.

04Ignoring chunk size

Reranking cannot fully fix badly chunked context.

05Skipping baselines

Compare against the original retriever.

06Measuring only recall

Also measure ranking quality, latency, cost, and final answer quality.

16

How to Evaluate Reranking

RECALL@KWas relevant evidence retrieved?
MRRHow high is the first relevant result?
NDCG@KAre relevant results ordered well?
PRECISION@KHow much of the final set is useful?
LATENCYHow much time did reranking add?
ANSWER QUALITYDid RAG answers improve?
Best practice: compare the same queries with and without reranking. Keep the candidate set and evaluation data consistent.
17

Practice: Build a Two-Stage Ranker

Create five candidate documents for a question. First give them retrieval scores. Then create a second relevance score and sort by the second score. Compare the original order with the reranked order.

TASK

Find the biggest ranking improvement

Identify a document that was not first after retrieval but becomes first after reranking. Explain why the second score is more useful.

Quick Quiz

1. What is reranking?

It is a second-stage process that reorders an initial set of retrieved candidates using a more detailed relevance score.

2. Why not rerank the whole database?

Reranking is usually more expensive, so it is applied to a smaller candidate set.

3. What is a cross-encoder?

It evaluates a query and candidate document together to produce a relevance score.

4. What is the main trade-off?

Higher retrieval quality can come with additional latency and compute cost.

30-Second Recap

1. Retrieve

Find a broad candidate set quickly.

2. Rerank

Score candidates more precisely.

3. Top-K

Keep only the best results for the next stage.

4. Evaluate

Measure quality, latency, cost, and answer impact.

Key Takeaways

  • Reranking is a second-stage retrieval step that improves the order of candidate results.
  • First-stage retrieval is optimized for speed and broad candidate recall.
  • Cross-encoders can evaluate query-document pairs more deeply than simple vector similarity.
  • Retrieve more candidates than you finally return, but keep the reranking set manageable.
  • Metadata and access constraints should be enforced separately from relevance scoring.
  • Reranking can improve RAG context quality but adds latency and compute cost.
  • Evaluate reranking against a strong baseline before adding it to production.