Advanced RAG: Chunking, Hybrid Search & Reranking

Generative & Agentic AI · Retrieval-Augmented Generation · Advanced · 24 min

Fix the common ways basic RAG fails: chunk documents well, combine keyword and vector search with reciprocal rank fusion, rerank and diversify the results, rewrite vague questions, and measure it all.

Two librarians search the same library: one by exact words on the spine, one by what the book is about. You merge their shortlists, then a careful expert reads the top few and puts the truly best one first.

The idea in everyday words

Hiring with two recruiters: one filters CVs by exact keywords ("Python", "AWS"), the other by overall fit. Each gives you a ranked shortlist. People near the top of BOTH lists are probably strong, so you merge the lists by rank. Then a senior engineer interviews the top ten and orders them properly. That is hybrid search, fusion and reranking.

Why basic RAG disappoints

Basic RAG (from the RAG lesson) is: split, embed, take the top-k most similar chunks, stuff them in the prompt. It fails in predictable ways:

Symptom Real cause Fix in this lesson
Answer misses a fact that is in the docs the fact was split across two chunks better chunking, overlap, parent-child
Exact codes like "E42" or a product SKU are not found embeddings are fuzzy about rare exact tokens hybrid search (keyword + vector)
The right chunk is ranked 8th, but you only send the top 5 similarity is not the same as relevance reranking
The top 5 chunks say the same thing near-duplicates crowd out other facts MMR (diversity)
Vague question, wrong chunks the query itself is poor query rewriting, HyDE, decomposition

The key idea: RAG quality is mostly retrieval quality. The LLM can only be as good as the context you hand it, so debug retrieval first.

Chunking strategies

A chunk is the unit you embed and retrieve. Size and boundaries decide what the model can see.

Strategy How it splits Good for
Fixed size every N tokens, with an overlap of 10 to 20% simple, predictable baseline
Recursive try paragraphs, then sentences, then words, until pieces fit general prose and markdown
Semantic start a new chunk where the meaning shifts (embedding distance between sentences jumps) long documents with topic changes
Hierarchical (parent-child) small child chunks for precise search, but return the larger parent section to the LLM manuals, contracts, anything where context around the hit matters

Tiny example: "Refunds take 5 days. They require a receipt." With fixed chunks of 4 words and no overlap, you get "Refunds take 5 days." and "They require a receipt." The second chunk no longer says what requires a receipt. Overlap, or a parent chunk, keeps the link.

Two cheap wins: add the document title and section heading to each chunk before embedding, and store metadata (source, page, date) for filtering and citations.

The key idea: small chunks search precisely, big chunks answer completely. Parent-child gives you both.

Hybrid search and reciprocal rank fusion

BM25 is the classic keyword ranking used by search engines. It scores a document higher when it contains the query's words, especially rare words, and does not over-reward long documents. It is great at exact matches (names, codes, acronyms).

Vector search is great at meaning ("money back" matches "refund"). Each catches what the other misses, so we run both and combine. That is hybrid search.

Problem: BM25 scores might be 0 to 25, cosine scores 0 to 1. You cannot just add them. Solution: ignore raw scores and use ranks.

Reciprocal Rank Fusion (RRF): for every document, add up 1 / (k + rank) over each list it appears in. k is a constant, commonly 60.

Doc BM25 rank Vector rank RRF score (k = 60)
A 1 3 1/61 + 1/63 = 0.0323
B 2 1 1/62 + 1/61 = 0.0325
C not found 2 1/62 = 0.0161

Order: B, A, C. Being near the top of both lists beats being first in one.

  • Small k (like 1) makes the top rank dominate. Large k (like 60) flattens the curve, so agreement across lists matters more.
  • On AWS: Amazon OpenSearch supports hybrid queries (keyword + k-NN) with score normalisation, and Bedrock Knowledge Bases offers a HYBRID search type for supported vector stores. Check the docs for which stores support it today.

Rerank and diversify

Embedding search is a bi-encoder: question and chunk are embedded separately, then compared. Fast, but shallow.

A reranker is a cross-encoder: it reads the question and one chunk together and outputs a relevance score. Much more accurate, much slower, so you only run it on a shortlist.

The standard funnel:

  1. Retrieve about 50 candidates (hybrid).
  2. Rerank them with a cross-encoder.
  3. Send the top 3 to 8 to the LLM.

On AWS, Amazon Bedrock offers reranker models (for example Amazon Rerank and Cohere Rerank) through a Rerank API, and Knowledge Bases can apply reranking inside a Retrieve call. Model availability differs by Region, so check the Bedrock docs. Open source: bge-reranker, or Cohere Rerank via API.

MMR (Maximal Marginal Relevance) fixes duplicates. Pick results one at a time, scoring each candidate as:

MMR = λ × relevance − (1 − λ) × (highest similarity to anything already picked)

With λ = 1 you get plain relevance. Lower λ pushes for variety. If chunk A is picked and chunk A2 is a near-copy of it (similarity 0.98), A2's score collapses and a different fact gets the slot.

The key idea: retrieve wide, then rank carefully, then remove repeats.

Better questions, and measuring the whole thing

Sometimes the problem is the question.

  • Query rewriting: ask an LLM to turn "and the cancellation thing?" into "What is the cancellation policy for annual plans?" using the chat history.
  • HyDE (Hypothetical Document Embeddings): ask the LLM to write a fake answer, embed that, and search with it. A fake answer looks more like real answer chunks than a short question does.
  • Decomposition: split "Compare the 2023 and 2024 refund rules" into two sub-questions, retrieve for each, then combine. Bedrock Knowledge Bases has a query decomposition option for this.

Measure, don't guess. Build a small test set of questions with known good chunks and answers, then track:

Metric Question it answers
Context precision of the chunks we retrieved, how many were relevant?
Context recall of the chunks we needed, how many did we retrieve?
Faithfulness is every claim in the answer supported by the retrieved context?
Answer relevance does the answer actually address the question?

Tools: Ragas (open source), LLM-as-a-judge, and Amazon Bedrock Evaluations, which can evaluate retrieval and generation for knowledge bases. Change one thing at a time (chunk size, k, reranker) and re-run the test set.

Go deeper (engineer level)

Retrieval metrics need labels. For each test question, record which chunk ids are relevant (a "qrels" file). Then:

  • recall@k: share of the relevant chunks found in the top k. The metric to watch before the reranker, because a chunk that is not retrieved can never be reranked up.
  • MRR (mean reciprocal rank): the average of 1 / (rank of the first relevant chunk). Good when one chunk is enough to answer.
  • nDCG@k: rewards putting the most relevant chunks highest, with graded labels (2 = answers it, 1 = related). Good for judging a reranker.

Generation metrics score the answer: faithfulness / groundedness (is every claim supported by the context?), answer correctness against a reference, and context precision (how much of what you sent was useful). Most are computed by an LLM judge. Judges have known biases (they favour longer answers, the first option shown and their own model family), so calibrate them on 50 to 100 human-labelled examples and report agreement.

Build the test set from real traffic. Sample production questions, add the hard cases (exact codes, multi-part questions, questions with no answer in the corpus) and keep it fixed so runs are comparable. Track p95 latency and cost next to quality, because a reranker adds a model call per query.

Failure modes to test for:

  • Lost in the middle: models use facts at the start and end of a long context better than the middle, so put the best chunks first and keep k small.
  • Query rewriting drift: HyDE or rewriting can invent details and retrieve confidently wrong chunks. Log the rewritten query.
  • Stale index: the right answer changed but old chunks still rank high. Add dates and filter on them.
  • No-answer questions: the system should say it does not know. Measure the refusal rate on purpose.

Step by step

  1. Query:

    User asks: "what does error E42 mean for a payment".

  2. BM25 list:

    Keyword search ranks d1 (contains "error", "E42", "payment") first, then d3 ("payment"). Vector-only search would have missed how important "E42" is.

  3. Vector list:

    Vector search ranks by meaning: d5 (declined payments) first, then d3, d1, d2.

  4. Fuse with RRF:

    k = 60. d1 = 1/61 + 1/63 = 0.03227, d3 = 1/62 + 1/62 = 0.03226, d5 = 1/61 = 0.01639, d2 = 1/64 = 0.0156. Fused order: d1, d3, d5, d2.

  5. Rerank:

    A cross-encoder reads the question with each chunk: d1 = 0.97, d5 = 0.71, d3 = 0.64, d2 = 0.02. New order: d1, d5, d3, d2.

  6. Diversify and send:

    MMR checks the top picks are not near-copies, then the top 3 go into the prompt with their source ids for citations.

Code example

docs = {
    "d1": "Error E42 means the payment card was declined.",
    "d2": "Refunds are processed within 5 business days.",
    "d3": "If a card payment fails, ask the customer to retry or use a different card.",
    "d4": "Our office dog is called Biscuit.",
    "d5": "Declined payments can happen when the bank blocks the charge.",
}
query = "what does error E42 mean for a payment"

# 1) Keyword search (a tiny stand-in for BM25): count shared words
def words(text):
    return set(w.strip(".,?").lower() for w in text.split())

kw_scores = {d: len(words(query) & words(t)) for d, t in docs.items()}
bm25 = [d for d in sorted(docs, key=lambda d: -kw_scores[d]) if kw_scores[d] > 0]

# 2) Vector search (pretend these cosine scores came from an embedding model)
cos = {"d5": 0.82, "d3": 0.80, "d1": 0.74, "d2": 0.30, "d4": 0.05}
vector = sorted(cos, key=lambda d: -cos[d])[:4]
print("BM25  :", bm25)
print("Vector:", vector)

# 3) Reciprocal rank fusion
def rrf(rankings, k=60):
    scores = {}
    for ranking in rankings:
        for rank, d in enumerate(ranking, start=1):
            scores[d] = scores.get(d, 0) + 1 / (k + rank)
    return sorted(scores, key=lambda d: (-scores[d], d)), scores

fused, s = rrf([bm25, vector])
print("RRF   :", [(d, round(s[d], 5)) for d in fused])

# 4) Rerank the shortlist with a (pretend) cross-encoder
rerank_score = {"d1": 0.97, "d5": 0.71, "d3": 0.64, "d2": 0.02}
final = sorted(fused, key=lambda d: -rerank_score[d])[:3]
print("Rerank:", final)

# 5) MMR: avoid near-duplicates
rel = {"A": 0.90, "A_copy": 0.89, "B": 0.70}
sim = {("A", "A_copy"): 0.98, ("A", "B"): 0.20, ("A_copy", "B"): 0.20}
pair = lambda x, y: sim.get((x, y), sim.get((y, x), 0))
picked, lam = [], 0.5
while len(picked) < 2:
    best = max((c for c in rel if c not in picked),
               key=lambda c: lam * rel[c] - (1 - lam) * max([pair(c, p) for p in picked], default=0))
    picked.append(best)
print("MMR picks:", picked, "(the near-copy A_copy was skipped)")

Complexity

  • Time: RRF: O(L) to accumulate over L total list entries, plus O(u log u) to sort the u unique docs. Reranking: one cross-encoder call per candidate, so keep the shortlist small.
  • Space: O(u) for the score table.

Interview tips

  • Walk through the funnel: hybrid retrieve about 50, rerank with a cross-encoder, MMR for diversity, send the top 5 with citations.

  • Explain why RRF fuses ranks instead of scores, and what the constant k does.

  • Bi-encoder vs cross-encoder: which is used for search, which for reranking, and why.

  • Know at least three chunking strategies and when parent-child chunking helps.

  • Name RAG metrics (context precision, context recall, faithfulness, answer relevance) and say you would build a fixed evaluation set before tuning.

Challenge: Reciprocal Rank Fusion

Write rrf(rankings, k) that fuses several ranked lists of document ids.

  • rankings is a list of lists; each inner list is ordered best first. Rank 1 is the first item.
  • A document's score is the sum of 1 / (k + rank) over every list it appears in. k is a whole number, k >= 0.
  • Return all ids, highest score first. If two scores are equal, order those ids alphabetically.

Example: rrf([["a", "b", "c"], ["b", "c", "d"]], 60) → ["b", "c", "a", "d"]

Solve it in the browser with tests, hints and an AI coach.

Practice problems

More in Retrieval-Augmented Generation

Previous: Vector Databases & Similarity Search · Next: Bedrock Knowledge Bases: Managed RAG