Skip to main content

The Great Reranking Championship: Where Documents Battle for Relevance πŸ₯Š

Published 8 min readMarkdown
Part of seriesSmart Legal QA β€” Building an AI Legal Assistant with RAG & LangChain
The Great Reranking Championship: Where Documents Battle for Relevance πŸ₯Š

Chapter 1: The Tournament Begins πŸ†

Picture this: You've just run your hybrid retrieval system, and it returns a magnificent collection of 50 candidate documents. They're all technically relevant to the user's query about "Section 302 IPC", but they're about as organized as a group of lawyers at a free buffet.
Some documents contain the exact phrase "Section 302". Others mention murder in passing. A few are from completely different legal codes but happen to discuss similar concepts. And one particularly ambitious document is just talking about "302 redirect errors" in a web development context (hey, even the best retrieval systems have their off days! πŸ€·β€β™€οΈ).

But here's the twist – your ensemble retriever has already done some internal reranking by combining BM25 and semantic scores with those 40/60 weights. So why rerank again? Because generic mathematical combinations can't capture the nuanced intelligence of legal domain expertise!

The Question: How do you decide which documents deserve the golden podium positions and which ones get sent home empty-handed?
The Answer: Welcome to the Great Reranking Championship! πŸŽͺ

Chapter 2: Meet the Contestants πŸ₯Š

In our legal AI arena, we have two heavyweight champions competing for the title of "Best Document Reranker":

πŸ₯Š Contestant 1: The Heuristic Hero (_rerank_documents)

"I judge documents the old-fashioned way – with rules, logic, and a healthy dose of domain expertise!"

πŸ₯Š Contestant 2: The SBERT Semantic Superstar (rerank)

"Embedding vectors and cosine similarity are all you need, baby! Let the neural networks decide!"

But here's the twist – they don't always fight each other. Sometimes they team up like a tag-team wrestling duo. Let's see how this championship unfolds!

Chapter 3: The Championship Rules πŸ“‹

Before our contestants enter the ring, let's understand when each fighter gets called into action. Your system has two different tournament formats:

Tournament Format 1: The Standard League

def retrieve_with_filters(self, query: str, filters: Optional[Dict] = None, k: int = 5) -> List[Document]:
    # Get initial results from ensemble retriever
    if self.has_bm25:
        docs = self.ensemble_retriever.get_relevant_documents(query)
    else:
        docs = self.semantic_retriever.get_relevant_documents(query)

    # Apply metadata-based filtering if filters are provided
    if filters:
        docs = self._apply_filters(docs, filters)

    # Rerank documents for better relevance
    docs = self._rerank_documents(docs, query)

In this format, The Heuristic Hero gets automatic entry. No questions asked, no tryouts needed. It's like being the defending champion.

Tournament Format 2: The Championship League

# Rerank the unique candidates using existing scorer and return top-k
try:
   reranked = self.rerank(uniq, query, top_k=k)
except Exception:
    reranked = self._rerank_documents(uniq, query)

In this premium format, The SBERT Semantic Superstar gets first shot at glory. But if it stumbles (maybe it's having a bad neural network day), The Heuristic Hero swoops in as the reliable backup.

Chapter 4: Round 1 - The Heuristic Hero Steps Into the Ring πŸ₯Š

Let's watch our first contestant in action:

def _rerank_documents(self, docs: List[Document], query: str) -> List[Document]:
    """Rerank documents based on relevance scoring"""
    scored_docs = []

    for doc in docs:
        score = self._calculate_relevance_score(doc, query)
        scored_docs.append((doc, score))

    # sort by score (descending)
    scored_docs.sort(key = lambda x: x[1], reverse=True)

    return [doc for doc, score in scored_docs]

Simple, elegant, no-nonsense. The Heuristic Hero doesn't mess around – it scores every document using its secret weapon: the _calculate_relevance_score function and then sorts them.

The Heuristic Hero's Scoring System πŸ“Š

But what makes this fighter so special? Let's peek into its training regimen:

def _calculate_relevance_score(self, doc: Document, query: str) -> float:
    """Calculate relevance score for a document"""
    score = 0.0
    content = doc.page_content.lower()
    query_lower = query.lower()

    # Extract phrase matching
    if query_lower in content:
        score += 2.0

Round 1: The Knockout Punch πŸ₯Š If the document contains the exact query phrase, it gets a massive 2.0-point boost. This is the haymaker – the knockout punch that says "This document is exactly what the user asked for!"

When someone searches for "Section 302", any document containing those exact words gets the champion's treatment.

    # Individual word matching
    query_words = query_lower.split()
    word_matches = sum(1 for word in query_words if word in content)
    score += (word_matches / len(query_words)) * 1.5

Round 2: The Combination Attack πŸ₯ŠπŸ₯Š Even if there's no exact phrase match, the Hero doesn't give up. It breaks down the query into individual words and rewards documents for each word they contain. This is like landing multiple smaller punches that add up to a powerful combination.

If you search for "murder under IPC" and a document contains 2 out of 3 words, it gets (2/3) * 1.5 = 1.0 points. Fair and mathematical!

    # Section reference bonus
    if re.search(r'section\s+\d+', content):
        score += 0.5

Round 3: The Legal Expertise Bonus βš–οΈ Here's where the Hero shows its domain knowledge. Any document that mentions "section" followed by a number gets a 0.5-point bonus. Why? Because in legal documents, section references are gold mines of specific information.

    # Document type relevance
    doc_type = doc.metadata.get('document_type', '')
    if doc_type in ['criminal_code', 'procedure_code'] and any(
        word in query_lower for word in ['criminal', 'police', 'arrest', 'bail']
    ):
        score += 0.8

Round 4: The Domain-Aware Finishing Move 🎯 And here comes the Hero's signature move! If someone asks about criminal matters (using words like "criminal", "police", "arrest", or "bail") AND there's a document from the criminal code or procedure code available, that document gets a whopping 0.8-point boost.

This is pure genius. The system knows that a question about police arrests should prioritize criminal procedure documents over, say, marriage law documents – even if both somehow mention "police."

The Final Score: Each document gets a total score that could range from 0 to potentially 4.8+ points, depending on how well it matches the query and domain context.

Chapter 5: Round 2 - The SBERT Semantic Superstar Enters 🌟

Now let's meet our second contestant. The SBERT Superstar is a bit more... sophisticated:

def rerank(self, candidates: List[Document], query: str, top_k: Optional[int] = None, alpha: float = 0.5) -> List[Document]:
    """
    Strong semantic reranker using SBERT:
     - compute embedding for query and candidate pages
     - compute cosine similarity
     - combine SBERT similarity with existing heuristic score:
         final_score = alpha * semantic_sim + (1-alpha) * normalized_heuristic_score
    """

The Superstar doesn't just look at words – it understands meaning. It's like having a contestant who can read minds!

The Superstar's Training Routine 🧠

# build texts to embed (use page content or small snippet)
texts = [(getattr(d, "page_content", "") or "")[:1500] for d in candidates]

try:
    q_emb = self._reranker_model.encode([query], convert_to_numpy=True)[0]
    doc_embs = self._reranker_model.encode(texts, convert_to_numpy=True)
except Exception:
    # embedding failed β€” fallback to existing heuristic reranker
    return self._rerank_documents(candidates, query)

The Superstar's secret weapon? Neural embeddings! It converts both the query and each document into high-dimensional vectors that capture semantic meaning. If this fails (maybe the GPU is having a coffee break), it again gracefully falls back to the Heuristic Hero.

The Superstar's Signature Combination Move 🎭

Here's where it gets really interesting:

def cosine(a, b):
    da = np.linalg.norm(a)
    db = np.linalg.norm(b)
    if da == 0 or db == 0:
        return 0.0
    return float(np.dot(a, b) / (da * db))

sem_sims = [cosine(q_emb, de) for de in doc_embs]

heur_scores = [self._calculate_relevance_score(d, query) for d in candidates]

The Superstar doesn't just rely on embeddings – it combines semantic similarity with the Heuristic Hero's scoring system! It's like a fusion technique in anime where two powerful fighters merge their abilities.

The magic happens with this formula:

final = alpha * sem + (1.0 - alpha) * h

The Magic Formula: final_score = alpha * semantic_similarity + (1-alpha) * normalized_heuristic_score

By default, alpha=0.5 meaning, it gives equal weight to both approaches. But this is configurable! You could make it more semantic-heavy (alpha = 0.7) or more heuristic-heavy (alpha = 0.3) depending on your needs.

Chapter 6: The Championship Strategies 🎯

Strategy 1: The Reliable Workhorse Route

# In retrieve_with_filters()
docs = self._rerank_documents(docs, query)

When you want consistent, predictable results, the Heuristic Hero gets the job done. It's fast, reliable, and doesn't need any fancy neural networks or GPUs. Perfect for production environments where you need guaranteed performance.

Strategy 2: The Heavyweight Championship Route

# In hybrid_retrieve()
try:
   reranked = self.rerank(uniq, query, top_k=k)
except Exception:
    reranked = self._rerank_documents(uniq, query)

When you want the absolute best quality and have the computational resources to support it, you go for the SBERT Superstar. But even then, you have the Heuristic Hero as backup insurance.

Chapter 7: The Tournament Results πŸ…

Here's how a typical reranking championship plays out:

Scenario 1: "What does Section 302 say?"

Heuristic Hero's Performance:

  • Document with exact "Section 302" text: 2.0 + 0.5 + 1.5 = 4.0 points

  • Document about murder (related): 0 + 0 + 0.5 = 0.5 points

  • Document from criminal code mentioning "Section": 0 + 0.5 + 0.8 = 1.3 points

Winner: The exact Section 302 document dominates!

SBERT Superstar's Performance:

  • Combines semantic understanding with heuristic scores

  • Might boost related murder documents if they're semantically similar

  • Final ranking balances exact matches with conceptual relevance

The Championship Trophy πŸ†

What makes this reranking system truly championship-worthy?

  1. Dual Strategy Approach: Two different reranking methods for different scenarios

  2. Graceful Fallbacks: If the advanced method fails, the reliable method takes over

  3. Domain Intelligence: Legal-specific scoring that understands the domain

  4. Semantic + Heuristic Fusion: Best of both worlds in the advanced reranker

  5. Production Ready: Handles failures, manages resources, and never crashes


Want to see more behind-the-scenes stories of building production AI systems? Follow along as we continue exploring the fascinating world of legal RAG systems, one component at a time!

No comments yet. Be the first to comment.

Smart Legal QA β€” Building an AI Legal Assistant with RAG & LangChain

Part 5 of 9

Documenting how I designed and built an AI assistant that can answer complex legal questions from uploaded PDFs. Learn about RAG pipelines, LangChain, embeddings, evaluation datasets, and architectural choices.

Up nextThe Confidence Game: How AI Learns to Know When It Doesn't Know 🎲Or: Why my legal AI sometimes calls for backup (and sometimes just goes for it)