Back to all posts
·7 min read

Finding the right context in RAG: chunking, hybrid search and reranking

When a RAG (retrieval-augmented generation) application gives a wrong or incomplete answer, the first reflex is usually to change the model or the prompt. A bigger model gets tried, new rules get added to the system message. Yet a large share of the problems come from information that never reaches the model at all: the right paragraph was not retrieved, the retrieved chunk was cut off mid-sentence, or the most relevant document sat in tenth place and never made it into the context window.

A model is only as good as the context it is given. In this post I look at the retrieval side of the RAG pipeline: how to chunk documents, why keyword and vector search should be used together, how to rerank results, and how to measure all of it.

Treat retrieval as a separate system first

Splitting the RAG pipeline into two parts makes things simpler: retrieval and generation. Generation writes an answer from the given context. Retrieval answers the question "which pieces of text does this question need?" Being able to test these two separately is very valuable.

In practice this means giving the retrieval component its own interface: it takes a question and returns ranked chunks together with scores and source information. The model call stays outside this interface. Then, when an answer is bad, you can first ask: was the right chunk among the top few results? If not, the problem is in retrieval; if it was, you need to look at generation. Without this separation, every improvement attempt is guesswork.

Chunking: meaning boundaries, not fixed length

The most common starting point is to split text into a fixed number of characters or tokens. It is easy to implement but ignores the structure of the document. A table gets split in two, the heading of a bullet list ends up in one chunk and its items in another, a code sample is cut in the middle. In the end, no chunk is meaningful on its own.

A better approach is to use the document's own structure. In Markdown or HTML content, headings are natural boundaries; splitting by headings first and then splitting sections that are still too long at paragraph boundaries works well. Tables and code blocks should be kept whole as a single chunk.

Two small additions also make a difference. First, prefix each chunk with the heading path it belongs to: a line like "Setup > Database > Connection settings" gives context to a paragraph that would otherwise be ambiguous on its own. Second, leave a small overlap between chunks; when an idea falls on the boundary between two chunks, a trace of it remains in both. The ideal chunk size depends on the content, so treat it not as a constant but as a parameter to be tuned by measurement.

public sealed record Chunk(
    string DocumentId,
    string HeadingPath,   // "Setup > Database > Connection settings"
    string Text,
    int Position);

Storing the chunk with its source document ID and position makes it easier later both to show citations and to reprocess only the affected chunks when a document is updated.

Why vector search alone is not enough

Embedding-based vector search is strong at finding text with similar meaning. A question like "I forgot my password" can find a paragraph that talks about "resetting credentials". But it is weak where exact matches matter: error codes, product codes, class and method names, version numbers, abbreviations. For a user asking about ERR_4012, the most relevant document is the one that contains that exact code, not one describing a semantically "similar" error code.

Classic keyword search (algorithms such as BM25) is good in exactly this case but misses synonyms and different phrasings. The strengths and weaknesses of the two methods complement each other. That is why the sensible default in production systems is to run both together: hybrid search.

Merging hybrid results

Scores from two different searches cannot be compared directly. A BM25 score and a cosine similarity live on different scales and are distributed differently from query to query. You can normalize the scores and take a weighted sum, but tuning the weights is tedious and fragile.

A simpler and more robust method is Reciprocal Rank Fusion (RRF), which uses ranks rather than scores. Each document gets 1 / (k + rank) points for its rank in each list, and the points are summed. k is a constant usually chosen around 60, which softens the effect of small differences among the top ranks.

public static IReadOnlyList<string> FuseByRank(
    IEnumerable<IReadOnlyList<string>> rankedLists, int k = 60)
{
    var scores = new Dictionary<string, double>();

    foreach (var list in rankedLists)
    {
        for (var rank = 0; rank < list.Count; rank++)
        {
            var id = list[rank];
            scores[id] = scores.GetValueOrDefault(id) + 1.0 / (k + rank + 1);
        }
    }

    return scores
        .OrderByDescending(pair => pair.Value)
        .Select(pair => pair.Key)
        .ToList();
}

A chunk that ranks high in both lists naturally rises to the top, while a chunk that is very good in only one list does not disappear entirely. Many databases and search engines support both full-text and vector search; keeping both in the same store also reduces the hassle of keeping two systems in sync.

Reranking: reading a few candidates more carefully

Hybrid search produces a good candidate list, but the ordering can still be coarse. Embedding models turn the question and the document into vectors separately; they do not look at the relationship between them together. Cross-encoder models used as rerankers, on the other hand, read the question and the chunk together and produce a relevance score. They are more accurate but slower.

That is why the common setup has two stages: hybrid search retrieves a wide candidate set (say 30–50 chunks), the reranker scores this set, and only the best few chunks are sent to the model. The expensive step thus runs on a small number of candidates.

The reranker score can also be used to set a threshold. If even the best chunk scores low, the model can be steered to say "the sources I have do not answer this". A model forced to answer from weak context is the one closest to making things up.

Metadata filters and permissions

Retrieval is not only a relevance problem. Users should only get answers from documents they are allowed to access. This filter should be applied in the search query itself, not just before results are sent to the model. Otherwise unauthorized documents fill up the candidate list, the results left after filtering are weak, and in the worst case unauthorized content reaches the model through a code path where the filter was forgotten.

Likewise, fields such as language, product, version or document type should be stored as metadata and be usable as filters in the query. Retrieving version 2 documentation for the question "how do I configure this in version 3?" is a technically relevant but practically wrong result.

Don't improve without measuring

Chunk size, overlap, hybrid search, the reranker and threshold values: all of these are tunable parameters, and when they are tuned by intuition, improving one can break another. The way to prevent this is a small but realistic evaluation set: a few dozen questions resembling real user questions, and for each one the documents or chunks that contain the answer.

On this set, two simple metrics are often enough. Recall@k shows whether the right chunk is among the first k results. MRR (mean reciprocal rank) measures how high the right chunk appears. Running these metrics after every change moves decisions from debate to measurement. And since these tests involve no model calls, they are fast and cheap and can run in the CI pipeline.

Growing the evaluation set over time matters too. Answers that users found poor are a good source of new examples where retrieval failed.

Conclusion

Most of RAG quality is decided before the model. Chunking documents with respect for their structure, combining vector and keyword search, reranking the candidate list and putting permission and metadata filters inside the query often make a bigger difference than switching models. None of this is complicated; the hard part is moving forward by measuring each step. Once you treat retrieval as a separate component with its own tests, the question "why did the model give a wrong answer?" stops being guesswork and becomes answerable.