RAGEngineering Hub
Chapter 7 · concept 1 of 6 · show all
  1. 1What RAG is, and why
    1. 1.1Why models need outside knowledge, and what hallucination means
    2. 1.2What RAG is: anatomy of a request
    3. 1.3RAG vs fine tuning vs long context and prompt caching
    4. 1.4Use cases and the quality, latency and cost triangle
    5. Chapter overview
  2. 2Tokens, cost and your first RAG
    1. 2.1Tokens and context windows for RAG
    2. 2.2The RAG lifecycle and your first RAG in miniature
    3. Chapter overview
  3. 3Getting documents in
    1. 3.1Content sources and file formats
    2. 3.2Parsing, layout and OCR
    3. 3.3Tables, images and mixed content
    4. 3.4Cleaning, normalization and quality gates
    5. 3.5Metadata, document identity and versioning
    6. 3.6Updates, deletes, reindexing and ingestion pipelines
    7. Chapter overview
  4. 4Chunking
    1. 4.1Why we chunk, and the main chunking strategies
    2. 4.2Structure aware chunking and tables
    3. 4.3Chunk size, overlap and token based sizing
    4. 4.4Contextual chunking and late chunking
    5. 4.5Parent child and multi representation indexing
    6. 4.6Chunk metadata, provenance and the chunking debugging playbook
    7. Chapter overview
  5. 5Embeddings
    1. 5.1Embeddings and similarity from first principles
    2. 5.2What embeddings cannot do
    3. 5.3Choosing an embedding model: size, cost, language
    4. 5.4Embedding model migration and index rebuilds
    5. Chapter overview
  6. 6Vector stores and scores
    1. 6.1Vector databases, ANN indexes and choosing a store
    2. 6.2Score calibration and thresholds
    3. 6.3Late interaction and multivector retrieval
    4. Chapter overview
  7. 7Finding the right chunks
    1. 7.1Query understanding, rewriting and expansion
    2. 7.2Dense retrieval and keyword search with BM25
    3. 7.3Hybrid retrieval and rank fusion
    4. 7.4topK, no good match, and metadata filtering
    5. 7.5Routing, diversity, deduplication and caching
    6. 7.6Reranking: two stage, cross encoder and LLM rerankers
    7. Chapter overview
  8. 8When retrieval fails
    1. 8.1Retrieval failure analysis playbook
    2. Chapter overview
  9. 9Building the answer
    1. 9.1Context selection, packing and citations
    2. 9.2Grounding prompts and abstention
    3. 9.3Lost in the middle and context management
    4. 9.4Conflicts, staleness and freshness rules
    5. 9.5Hallucination checks and answer verification
    6. 9.6Conversational RAG, answer UX and RAG APIs
    7. Chapter overview
  10. 10Measuring
    1. 10.1Why measure, and what to measure
    2. 10.2Building a golden dataset
    3. 10.3Retrieval metrics: precision, recall, MRR, nDCG
    4. 10.4Faithfulness and answer correctness
    5. 10.5LLM as judge, and judging the judge
    6. 10.6Offline and online evals, regression tests and slices
    7. Chapter overview
  11. 11Safety and operations
    1. 11.1Prompt injection and poisoned documents
    2. 11.2Access control, privacy and governance
    3. 11.3Index lifecycle operations
    4. 11.4Observability and tracing
    5. 11.5Latency, cost, caching and model routing
    6. 11.6Reliability, degraded modes and launch readiness
    7. Chapter overview
  12. 12Scale and advanced RAG
    1. 12.1Scaling, multi tenancy and enterprise architecture
    2. 12.2Choosing an architecture: naive, advanced, agentic, graph
    3. 12.3Agentic RAG and RAG as an MCP tool
    4. 12.4GraphRAG, structured data and multimodal RAG
    5. Chapter overview

Query understanding, rewriting and expansion

Users type short, vague or follow-up questions. Rewriting can fix that, or break it. We searched 12 questions in full and as short keywords; the same change helped one question and buried another.

A real question

A user types “laptop theft max”. Should the system rewrite it before searching?

Sometimes. Rewriting turns vague or follow-up questions into searchable ones. It can also drop the very words that found the answer. Measure each rewrite on your golden set.

The problem

Why this matters

Rewriting or expanding the question always improves retrieval.
The belief

Rewriting or expanding the question always improves retrieval.

We wrote short keyword forms of 12 golden questions. Vector search found 10 of 12 either way, but individual ranks moved both ways: one answer went from rank 4 to 2, another from rank 1 to 13.
What really happens

We wrote short keyword forms of 12 golden questions. Vector search found 10 of 12 either way, but individual ranks moved both ways: one answer went from rank 4 to 2, another from rank 1 to 13.

Why not the simpler way

Real questions are not like golden-set questions. They are short ("dividend"), vague ("is it covered?"), full of typos, or depend on the conversation ("and in 2024?"). Search runs on the literal text, so a vague question gets vague results. Query understanding fixes the question before retrieval.

The idea

The idea in plain words

Rewriting turns the user's text into a better search query, usually with a small model. Expansion adds alternatives: synonyms, several phrasings (multi-query), or a hypothetical answer to search with (HyDE, Gao et al., arXiv 2212.10496). Decomposition splits a question with two parts into two searches.

A librarian who hears "that book about the war, the red one" asks a few questions before going to the shelves.

How it works

Step by step

  1. In a chat, rewrite follow-ups into stand-alone questions: “What does the second plan cost?” instead of “and that one?”.
    1

    Resolve the conversation

    In a chat, rewrite follow-ups into stand-alone questions: “What does the second plan cost?” instead of “and that one?”.

  2. Multi-query: generate a few versions, search each and fuse the results. HyDE: search with a drafted answer instead of the question.
    2

    Or search several phrasings

    Multi-query: generate a few versions, search each and fuse the results. HyDE: search with a drafted answer instead of the question.

  3. Run the golden set with and without the rewrite. Keep exact codes, numbers and dates unchanged in every version.
    3

    Keep it only if it helps

    Run the golden set with and without the rewrite. Keep exact codes, numbers and dates unchanged in every version.

In detail

Conversational rewrite. Give a model the last few turns and the new message; ask for one stand-alone question. Log both the original and the rewrite: when follow-ups fail, the rewrite is the first thing to check.

Multi-query. Ask for 3 phrasings, search each, fuse with RRF (RAG-28). On our 12 questions, fusing the full and short vector results found the same 10 as the full question alone: no gain, and an extra search.

HyDE. Ask a model to write a plausible answer, embed it, and search with that. Answers look more like documents than questions do. The risk is a made-up detail that pulls in the wrong chunk.

Guard exact terms. Extract codes, amounts and dates with a regex before rewriting and check they survive.

The code

Try it in Python

import re

REWRITE = """Rewrite the last user message as one stand-alone search question.
Keep every code, number and date exactly as written. Output only the question.

Conversation:
{history}
Last message: {message}"""

def guard(original: str, rewritten: str) -> str:
    exact = re.findall(r"[A-Z]{1,4}-?\d[\w.-]*|\d+(?:[.,]\d+)?", original)
    return rewritten if all(e in rewritten for e in exact) else original

See it

What we measured

Measured · answer chunk in the top 3, 12 golden questions

Polder corpus, 34 recursive 512 token chunks. Short keyword forms written by us for 12 golden questions. Vector: bge-small. Multi-query: RRF of the full and short vector lists.

Vector, full question10 of 12
Vector, short form1010 of 12
Vector, both fused (multi-query)1010 of 12
BM25, full question12 of 12
BM25, short form1211 of 12

Measured 2026-11-04 with corpus/scripts/measure-parts-4-7.mts. No model-written rewrites were tested; those need a model call per question (not measured yet: needs an API key).

Try it on a real example

Full question against a short keyword form, vector search, rank of the answer chunk

Case

g-19

Full: “Within how many days must I report home contents damage?” → rank 4
Short: “report damage days” → rank 2

The answer sits in the general conditions: “A claim must be reported within 14 days…”. The short form keeps just those words, and the answer moved up two places.

Choosing

Use it when, avoid it when

Use it when
  • Rewriting follow-ups into stand-alone questions in chat
  • Multi-query or HyDE where the golden set shows a gain
Avoid it when
  • Rewriting questions that contain exact codes without a guard
  • Adding expansion because a tutorial did

What it costs · One small model call per question, plus one extra search per added phrasing.

In production

Every rewrite adds a model call before search, usually a few hundred milliseconds and a small cost per question. Route: rewrite follow-ups in chat, leave stand-alone questions with exact codes alone. Track per-slice results; short keyword questions and follow-ups behave differently from full questions.

Watch out

Common mistakes

  • Shorter, cleaner queries search better. “laptop theft max” fell from rank 1 to 13.
  • Rewriting is only for typos. Its biggest job is follow-up questions.
  • Multi-query always raises recall. It added nothing on our 12 questions.

Check yourself

Remember this

Remember these

  • In chat, rewriting follow-ups into stand-alone questions is the clear win.
  • Multi-query and HyDE add model calls; test them before keeping them.
  • Never let a rewrite change codes, numbers or dates.
  • On our 12 test questions, short forms kept the total but moved ranks both ways.

Say it in an interview

  1. 01I rewrite follow-up questions into stand-alone ones; that is the clear win in chat.
  2. 02I treat multi-query and HyDE as experiments, kept only if the golden set improves.
  3. 03On my corpus a short keyword form moved one answer from rank 4 to 2 and another from 1 to 13.
  4. 04A guard checks that codes, numbers and dates survive the rewrite.
  5. 05I log the original and rewritten query so follow-up failures are easy to trace.

Quick quiz

Three questions

Question 1

Q1

"laptop theft max" instead of the full question did what to vector search?

Question 2

Q2

What is the most important use of query rewriting in a chat?

Question 3

Q3 · from RAG-20

Why can a near-identical question still need a different answer?

Saved on this device. No account needed.