Artificial Intelligence • AI Application Engineering • 5 min read

RAG: Chunking, Indexing, and Reranking

A university assistant receives a question about registration deadlines. The answer is somewhere in a 90-page student handbook, but giving the entire handbook to a language model is expensive and confusing. Chunking, indexing, and reranking let the assistant find the most useful paragraphs first.

1. Where these steps fit

A retrieval-augmented generation (RAG) system has two broad phases. During indexing, it prepares source material so it can be searched. During query-time retrieval, it selects passages to place in the generator’s context.

  1. Parse and clean documents while retaining source identifiers.
  2. Divide text into retrievable chunks.
  3. Build a keyword index, vector index, or both.
  4. Retrieve candidate chunks for a new question.
  5. Apply security filters and, optionally, a reranker.
  6. Assemble evidence, cite sources, and generate an answer.

Indexing is often repeated when documents change; querying happens for each user request.

2. Chunking: choosing what can be retrieved

A chunk is a retrievable unit of content, such as a paragraph or short section. The goal is to keep enough context for an answer without forcing unrelated material into the model prompt.

Fixed-size and structural chunking

Fixed-size chunking splits content after a chosen number of tokens or characters. It is simple, but it may cut a definition in half. Structure-aware chunking follows headings, paragraphs, tables, or document sections. It often preserves meaning better, especially in policies and technical manuals.

Overlap repeats a small amount of text between adjacent chunks to protect boundary-spanning facts. Excessive overlap creates near-duplicates and wastes storage and context. Chunk size and overlap are tuning choices, not universal constants.

Worked example

A handbook contains:

Registration closes on 12 September. Late requests require department approval. Appeals go to the registrar within five working days.

If the chunk ends after the first sentence, a question about late registration may retrieve the deadline but miss the approval rule. A chunk that preserves the short paragraph keeps the conditions together.

For tables, store headers with cells; for code, preserve function or class boundaries; for PDFs, remove repeated page footers without discarding page references.

3. Indexing: making chunks searchable

An inverted index maps terms to documents or chunks that contain them. Ranking methods such as BM25 favor useful term matches. A vector index stores numerical embeddings and supports nearest-neighbor search for semantic similarity. Neither index is universally better.

Index typeStrong atCommon limitation
Keyword/BM25Exact terms, IDs, rare names, error codesDifferent wording may miss relevant text
Vector similarityRelated meanings and paraphrasesCan overlook exact identifiers or return vaguely related chunks
HybridCombining lexical and semantic evidenceRequires score or rank fusion and extra evaluation

Store metadata: document title, publication date, section, permissions, and a stable source reference. Filter access rights before context is exposed to the generator, not merely after the answer is written.

4. Retrieval and reranking

The first search stage typically favors speed: retrieve the top k candidates from one or more indexes. A reranker then scores the query with each candidate more carefully and orders the candidates again. Cross-encoder rerankers can inspect a query and candidate jointly but cost more computation than embedding similarity.

Example: a query about Python list sorting stability could retrieve a page about sorting algorithms generally and another page documenting Python’s stable sort. A reranker should put the precise Python passage first.

Reranking cannot repair an omitted candidate. If the relevant chunk never enters the candidate set, improve recall, chunking, or indexing before adjusting the reranker.

5. Practical retrieval experiment

The following standalone Python example illustrates a small keyword retriever. It is not a production BM25 or embedding index, but it makes the candidate-selection step visible.

import re

passages = [
    'Registration closes on 12 September.',
    'Late registration needs department approval.',
    'Examinations begin in December.',
]
query = 'Who approves late registration?'

def tokens(text):
    return set(re.findall(r'[a-z]+', text.lower()))

query_terms = tokens(query)
ranked = sorted(
    passages,
    key=lambda p: len(query_terms & tokens(p)),
    reverse=True,
)
print(ranked[0])

In a real system, compare BM25, embeddings, and hybrid retrieval on labeled questions; measure the cost of optional reranking as well as its accuracy benefit.

6. Evaluate the retrieval stage separately

  • Recall@k: Fraction of relevant material recovered in the first k candidates; especially important before reranking.
  • Precision@k: Fraction of retrieved candidates that are relevant.
  • MRR: Rewards placing the first relevant result near the top.
  • nDCG: Rewards a ranking that puts highly relevant results earlier.
  • Answer groundedness: Tests whether the final generated claims actually follow from the retrieved evidence.

Use a representative question set including paraphrases, dates, named entities, ambiguous requests, and questions with no answer in the source material. Check that deleting or revising a source causes the index to update.

7. Common failures and design choices

Too-small chunks lose context; too-large chunks dilute relevance. Stale indexes surface old policies. Duplicate pages fill the top results with the same evidence. Embedding-only search may mishandle exact course codes. Rerankers may be too slow for stringent latency limits.

Prefer improving source quality and retrieval recall before adding orchestration complexity. Store source offsets or URLs so answers can cite the passage the system actually used.

References

Related articles in

Image preview

Fit