Skip to content
~/series/production-rag/retrieval-and-reranking
EST: 32mSECTIONS: 11SKILLS: 5

Lesson 5 · Production RAG

32 min readAdvanced

Retrieval and reranking

Hybrid search, reranking, and the production retrieval stack that produces precise context.

Finding POL-4412 when meaning and exact text disagree

Step 1 of 5

Vector search

The query 'POL-4412 cancellation window' finds chunks about cancellation by meaning, but it can miss the policy number, which carries little meaning to an embedding.

Each stage fixes a failure of the one before it, and the permission filter runs inside the query.

Retrieval and reranking

Retrieval finds candidate chunks relevant to a query. Reranking re-scores those candidates with a more accurate, computationally intensive model to select the best top-k context.

Modern production retrieval pairs two-stage hybrid search with three advanced patterns:

1. Contextual Retrieval: during ingestion, a lightweight model prefixes each chunk with a concise summary of its parent document and section context. Chunks like 'the fee is 3%' become 'ACME Enterprise Merchant Agreement, Section 4.1 Payment Terms: the fee is 3%', eliminating decontextualised retrieval failures.

2. Corrective RAG (CRAG) & Agentic RAG: a lightweight grading step evaluates candidate relevance. If retrieval confidence is low or ambiguous, the agent rewrites the query, searches a secondary source, or triggers a web search fallback.

3. GraphRAG: knowledge graphs and hierarchical community summaries connect entities across disparate documents, allowing multi-hop reasoning and high-level thematic queries.

Why two stages and beyond

Vector search alone (cosine similarity) is fast but imprecise — it ranks semantically-adjacent-but-factually-irrelevant chunks highly. A cross-encoder reranker (which processes query AND document jointly with full cross-attention) provides massive precision gains but is too computationally expensive to run over the entire index.

Adding Contextual Retrieval ensures that isolated chunks carry their document identity into the vector and BM25 index. Adding CRAG ensures the system detects when retrieval has failed before hallucinating an answer. Adding GraphRAG community summaries ensures multi-document queries don't miss cross-cutting facts.

Production retrieval stack

Production pipeline:

Query → Query decomposition / CRAG grading loop → Parallel search:

Contextual dense vector search (pgvector, top-20)
BM25 / full-text keyword search (top-20)
GraphRAG entity & community summary lookup

→ Reciprocal Rank Fusion (RRF) → Cross-encoder reranker (Cohere/BGE, top-5) → RBAC permission filter → Context assembler for LLM.

Every candidate chunk contains its contextual prefix, source citation metadata, and relevance score.

Hybrid search + reranking

retrieval.py
import psycopg
from pgvector import Vector
from pgvector.psycopg import register_vector
import cohere

co = cohere.ClientV2()
conn = psycopg.connect("dbname=rag")
register_vector(conn)

# Access control: every query takes the caller's permission groups and filters
# on them in SQL, so chunks the caller may not read are never returned.
# There is no "no filter" path. (With an approximate index, filtering can
# return fewer than k rows; see pgvector's notes on filtering.)

def vector_search(query_embedding: list[float], groups: list[str], k: int = 20) -> list[dict]:
    """ANN vector search (cosine distance), filtered by permission group."""
    emb = Vector(query_embedding)
    rows = conn.execute(
        """
        SELECT id, text, source, section, embedding <=> %s AS distance
        FROM chunks
        WHERE permission_group = ANY(%s)
        ORDER BY embedding <=> %s
        LIMIT %s
        """,
        (emb, groups, emb, k),
    ).fetchall()
    return [{"id": r[0], "text": r[1], "source": r[2], "section": r[3], "score": 1 - r[4]} for r in rows]

def full_text_search(query: str, groups: list[str], k: int = 20) -> list[dict]:
    """PostgreSQL full-text search ranked with ts_rank (keyword matching, not BM25)."""
    rows = conn.execute(
        """
        SELECT id, text, source, section,
               ts_rank(tsv, plainto_tsquery(%s)) AS rank
        FROM chunks
        WHERE tsv @@ plainto_tsquery(%s)
          AND permission_group = ANY(%s)
        ORDER BY rank DESC
        LIMIT %s
        """,
        (query, query, groups, k),
    ).fetchall()
    return [{"id": r[0], "text": r[1], "source": r[2], "section": r[3], "score": r[4]} for r in rows]

def rrf_fuse(vector_results: list[dict], text_results: list[dict], k: int = 60) -> list[tuple[str, float]]:
    """Reciprocal Rank Fusion — combine rankings without score calibration."""
    scores: dict[str, float] = {}
    for results in (vector_results, text_results):
        for rank, r in enumerate(results):
            scores[r["id"]] = scores.get(r["id"], 0) + 1 / (k + rank + 1)
    return sorted(scores.items(), key=lambda x: -x[1])

def rerank(query: str, candidates: list[dict], top_k: int = 5) -> list[dict]:
    """Cross-encoder rerank — reads query + doc jointly."""
    docs = [c["text"] for c in candidates]
    # Rerank model ids from docs.cohere.com/docs/rerank (checked 28 October 2026); they change, so check the list.
    results = co.rerank(model="rerank-v5.0-pro", query=query, documents=docs, top_n=top_k)
    return [{**candidates[r.index], "score": r.relevance_score} for r in results.results]

def retrieve(query: str, query_embedding: list[float], groups: list[str]) -> list[dict]:
    v = vector_search(query_embedding, groups, k=20)
    t = full_text_search(query, groups, k=20)
    by_id = {c["id"]: c for c in v + t}
    candidates = [by_id[cid] for cid, _ in rrf_fuse(v, t)[:20]]
    return rerank(query, candidates, top_k=5)

Experiment: retrieval strategy

Compare vector-only, keyword-only (full-text), and hybrid+rerank on different query types.

Choose a retrieval strategy and a query type. See how each performs.

What to observe

Vector search wins on semantic/paraphrased queries. Keyword (full-text) search wins on exact identifiers (policy numbers, code names, article numbers). Hybrid + rerank is robust across all query types — that's why it's the production default. Never ship vector-only over mixed content.

Production retrieval

Production retrieval: hybrid (vector + full-text) with RRF fusion, cross-encoder reranking to top-5, permission filtering in every SQL query (not at display), query rewriting for multi-turn conversations, caching of embeddings and rerank results, and observability on scores at every stage. Online eval samples retrieval quality in production.

Challenge

A user searches for 'POL-4412 cancellation window'. Vector search returns chunks about cancellation but misses the policy number. Keyword search returns the policy but ranks an outdated version first. Design a retrieval system that returns the current version of POL-4412 with its cancellation window.

Production checklist

Production checklist

0 of 8 checked

Knowledge check

Why is the metadata (RBAC) filter applied in the SQL WHERE clause, not after retrieval?

Complete

You now have the full production retrieval stack. This completes the Production RAG series. Next step: build the RAG Assistant project, or explore evaluation.

Mark this chapter as complete

Track your progress and unlock the next chapter.

Email updates

Get the next chapter and new guides by email.

One email per substantial release. Unsubscribe in one click.

We will email you a confirmation link first, then send an occasional email when a substantial guide is published. Unsubscribe in one click. Stored with our email provider (Resend), never sold or shared. See the privacy policy.

Continue learning