# 6. Advanced retrieval

Techniques that make retrieval precise. BM25 keyword search, hybrid search and reciprocal rank fusion, cross-encoder reranking, query rewriting and expansion, context compression and parent-child chunking.

Source: https://glamorous-boar.cloudvent.net/learn/advanced-retrieval/

---

Basic RAG embeds the question and takes the top-k chunks. Production RAG adds stages before and after that step. A typical advanced pipeline:

**rewrite query → hybrid search (vector + keyword) → rerank → compress → build context → generate → verify**

## BM25 keyword search

**BM25** (Robertson and colleagues, *Okapi BM25*) is the classic ranking function of search engines. It scores a document for a query by summing, over query terms:

- **term frequency**: how often the term appears in the document, with diminishing returns (the 10th occurrence adds less than the 2nd);
- **inverse document frequency (IDF)**: rare terms count more than common ones (*refund* matters more than *the*);
- **length normalisation**: long documents do not win just by being long.

Strengths: exact matches for codes, names, IDs and rare words; no model needed; fast; explainable. Weaknesses: no understanding of synonyms or paraphrase. Stemming (*travel*, *traveling*, *traveled* → *travel*) helps a bit.

## Hybrid search

Vector search understands meaning; BM25 nails exact terms. **Hybrid search** runs both and fuses the rankings. The problem: their scores are on different scales (cosine 0–1 vs BM25 0–∞), so you cannot just add them.

### Reciprocal rank fusion (RRF)

**RRF** (Cormack, Clarke and Büttcher, 2009) ignores scores and uses only **ranks**:

`RRF(d) = Σ over result lists of 1 / (k + rank of d in that list)`

with k ≈ 60. A document ranked 1st by vectors and 3rd by keywords scores 1/61 + 1/63. RRF is robust, needs no tuning, and is the default in AgenticMind's Hybrid Search. The alternative, **weighted fusion**, min-max normalises each list's scores and mixes them (`vector_weight`), which can be tuned but is more sensitive.

Hybrid search also works across **query variants**: retrieve for the original question and two paraphrases, then fuse all lists.

## Reranking

First-stage retrieval uses **bi-encoders**: the question and each chunk are embedded *separately*, which is fast enough to search millions of chunks but compresses each into one vector. A **cross-encoder** reads the question and a chunk *together* and outputs a relevance score. It is far more accurate (it sees word-level interactions) and far too slow to run over a whole corpus, so it is used as a **second stage** on the top 20–50 candidates (Nogueira and Cho, 2019, *Passage Re-ranking with BERT*).

| | Bi-encoder (embedding) | Cross-encoder (reranker) |
|---|---|---|
| Input | Query and document separately | Query and document together |
| Speed | Precompute document vectors; search millions | Score each pair at query time |
| Accuracy | Good | Better |
| Role | First stage: recall | Second stage: precision |

LLMs can also rerank (score each passage 0–10), at higher cost. Rerank scores make a good **confidence signal**: a low best score suggests the question is not answerable from the corpus.

## Query rewriting and expansion

Users ask messy questions; retrieval needs good queries.

- **Standalone rewriting**: in a conversation, *and for part-timers?* becomes *How much annual leave do part-time employees get?* using chat history.
- **Multi-query expansion**: generate several phrasings and retrieve for each (fused with RRF), covering vocabulary the user did not use.
- **HyDE** (Hypothetical Document Embeddings; Gao et al., 2022): ask the model to write a hypothetical answer and embed *that*, since answers resemble documents more than questions do.
- **Step-back / decomposition**: retrieve for a broader question or for each sub-question of a multi-hop question.

Always fall back to the original query if rewriting fails: never let a helper step block retrieval.

## Context compression

Retrieved chunks contain sentences irrelevant to the question. **Compression** keeps only the relevant ones, so the prompt is shorter, cheaper and less distracting:

- **Extractive**: score sentences against the query (e.g. BM25), keep the top few plus neighbours for continuity, in original order.
- **LLM-based**: a model selects relevant sentences. To avoid introducing text the source never said, accept only sentences that literally occur in the source (AgenticMind enforces this).

## Parent-child (small-to-big) retrieval

Small chunks match precisely; large chunks give the model context. **Parent-child chunking** gets both: index small **child** chunks, each linked to a larger **parent** section; retrieve children, then replace them with their parents (de-duplicated, keeping the best child score) before building the prompt.

Related ideas: **sentence-window retrieval** (return the matched sentence plus neighbours) and **contextual chunk headers** (prefix each chunk with its document title and section path before embedding, sometimes called contextual retrieval).

## Metadata filtering

Filters narrow the search space before ranking: one document, a date range, a language, a tenant or a permission group. They make retrieval faster, more precise and, for multi-tenant systems, secure.

## Measuring retrieval

Change one stage at a time and measure **recall@K** (did the right chunk make the top K?), **MRR** (how high was the first right chunk?) and **NDCG** (rank-weighted relevance) on a labelled set (chapter 12). Many techniques help on one corpus and do nothing on another: on a small, clean handbook, vector search alone may already rank perfectly.

## Try it in AgenticMind

| Technique | Node |
|---|---|
| BM25 | **Keyword Search** (index built by Index Documents) |
| Hybrid + RRF / weighted fusion | **Hybrid Search** (`fusion`, `rrf_k`, `vector_weight`, `queries` input) |
| Cross-encoder / LLM reranking | **Reranker** (`fastembed` cross-encoder by default) |
| Standalone rewriting + multi-query | **Query Rewriter** (`history` input, `variants`) |
| Compression | **Context Compressor** (`extractive` or `llm`) |
| Parent-child | **Chunker** `parent_child` + **Parent Expander** |
| Structure-aware chunking | **Chunker** `layout`, `markdown`, `sentence`, `semantic` |
| Filters | `filters` on Retriever, Keyword Search, Hybrid Search |

Template: *Advanced RAG (hybrid search + reranking)*. Compare it with *RAG answers with citations* in the Evaluation Lab.

<Alert variant="tip" title="Key takeaways" text="BM25 catches exact terms; embeddings catch meaning; hybrid search with reciprocal rank fusion gets both without tuning. Cross-encoder rerankers add precision on the top candidates. Rewrite queries for conversations and coverage, compress context to cut noise, and use parent-child chunks for precise matching with full context. Measure each change."/>
