Interview's MateAI Engineering
Interview's Mate

AI Engineering

LLMs, RAG, agents & evals

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
AI Engineering topics
Lesson 31/ 160
02. RAG

Query Rewriting

Expand, rewrite, or decompose user questions into better retrieval queries.

IntermediateExpansion · Decomposition3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidHands-onQuiz (3)Practice

In plain words

Before searching, the system rewrites the question into clearer, standalone search requests, so the search tool actually finds the right pages.

Think of it like…

A reference librarian turning your vague request into proper catalogue searches: they ask what you were discussing, split "compare X and Y" into two lookups, and try a few synonyms, then bring back the combined results.

Where you’ve seen it

An HR assistant receives the sequence "What's the parental leave policy?" then "and for contractors?". Searching the second message alone returns generic contractor documents. A rewriting step with the chat history produces "parental leave policy for contractors", and retrieval hits the right clause. On 300 logged multi-turn conversations, recall@5 for follow-up questions rises from 52 to 83 percent, at about 350 ms added by a small model.

Words you’ll hear

Standalone query
A question rewritten so it makes sense without the conversation history.
Query expansion
Adding synonyms, acronyms or related terms to improve recall.
Query decomposition
Splitting a complex question into simpler sub-questions answered separately.
Multi-query retrieval
Several rewrites each retrieve results, which are merged (often with RRF).

Visual diagram

Loading interactive diagram

Theory & deep dive

Techniques and when to use them

Contextual rewriting takes the conversation history plus the latest message and outputs a standalone query; it's the single most valuable technique for chatbots. Expansion adds acronyms and synonyms ("PTO" → "paid time off, annual leave") and helps lexical search the most. Decomposition splits "Compare the 2024 and 2025 refund policy and say which is stricter" into two retrievals (one per year) plus a final comparison; it's the foundation of multi-hop and agentic RAG. Multi-query asks the LLM for 3 to 5 paraphrases or angles, retrieves for each and fuses results, trading extra retrievals for robustness to phrasing. Step-back prompting asks a more general question first ("What are the rules for refunds?") to retrieve background.

Use structured output (a JSON list of queries with an optional filter such as year or document type) so the rewrite can also set metadata filters. A classifier or rules can skip rewriting for already-clear queries, saving cost.

A rewrite prompt with structured output

"Given the chat history and the latest question, return JSON {\"queries\": [up to 3 standalone search queries], \"filters\": {\"year\": number|null}}. Preserve names, numbers and codes exactly." The instruction to preserve identifiers prevents the model from paraphrasing away what BM25 needs.

Key takeaway: Contextual rewrite for chat, decomposition for multi-part questions, multi-query for robustness.

Risks, cost and evaluation

Rewrites cost an extra LLM call (use a small, fast model; 200 to 600 ms is typical) and can hurt: the model may drop an important constraint, add assumptions, translate technical terms or invent details. Mitigate by retrieving with both the original and rewritten queries, instructing the model to preserve exact terms, keeping rewrites short, and falling back to the original if the rewriter fails or times out. Multi-query multiplies retrieval load; fuse results and cap the number of rewrites.

Evaluate on real, logged queries (including multi-turn conversations and ambiguous short queries), with labelled relevant documents. Compare recall@k and answer quality: original only, rewritten only, and original plus rewrites. Slice results by query type: follow-ups usually gain the most, while clear single-turn questions may gain nothing or even lose. Log rewrites in production so you can inspect failures and tune prompts, and watch added latency at p95.

Results by query type

Follow-up questions: recall@5 52% → 83%. Multi-part questions with decomposition: 61% → 79%. Clear single-turn questions: 88% → 87% (no gain), so a simple check skips rewriting for them.

Key takeaway: Include the original, preserve exact terms, and measure gains by query type.

How it works, step by step

Step 1 of 4
Analysis

1. Collect real problem queries

Pull logged follow-ups, vague and multi-part questions where retrieval failed and label what should have been found.

300 multi-turn conversations
Key numbers at this step
Slice
by query type

When to use it & trade-offs

What it is

Users don't write good search queries: "what about for contractors?" depends on the previous turn, "compare the 2024 and 2025 refund policy" needs two searches, and "stuff about leave" is vague. Query rewriting uses an LLM (or rules) to transform the raw input into one or more better retrieval queries before searching. Main techniques: contextual rewriting (make a follow-up standalone), expansion (add synonyms and related terms), decomposition (split a multi-part question into sub-queries) and multi-query (generate several paraphrases, retrieve for each, fuse the results).

Why it matters: Retrieval can only find what the query asks for. In chat, the latest message alone is often unsearchable, and complex questions need several retrievals. A cheap rewriting step frequently improves recall more than switching embedding models, but it adds latency and can drift from what the user meant, so it must be measured rather than assumed.

When to reach for it

  • Chatbots over knowledge bases
  • Questions comparing items or time periods
  • Short or jargon-heavy queries that miss synonyms

When to avoid or be careful

  • Rewriting every query without measuring gains
  • Dropping the original query from retrieval
  • Letting the rewriter paraphrase codes and names

Query rewriting techniques

Contextual (standalone) rewrite
Best for: Chat assistants with follow-up questions

Strengths: Large recall gains on ambiguous turns.

Watch out: Extra LLM call; can drop constraints.

Expansion / multi-query
Best for: Vague or vocabulary-mismatched queries

Strengths: Robust to phrasing; boosts recall.

Watch out: More retrievals; possible noise.

Decomposition
Best for: Multi-part or multi-hop questions

Strengths: Each sub-question retrieves precisely.

Watch out: Several calls plus a synthesis step.

Interview signals & numbers to know

When this topic comes up

  • “Follow-up questions retrieve nothing useful”
  • "Compare X and Y" questions
  • “What is multi-query retrieval?”
  • Conversational search
  • Agentic retrieval

Benchmarks & rules of thumb

3 – 5 -
typical number of generated queries
200 – 600 ms -
added by a small rewriting model
52% → 83% -
follow-up recall@5 in the example

Common mistakes & follow-ups

Common interview mistakes

  • Rewriting "ERR_4012 on plan X7" into prose and losing the exact tokens.
  • Adding five rewrites to every query and multiplying retrieval cost for no gain.
  • Not logging rewrites, so no one can tell why retrieval went wrong.

Likely interviewer follow-ups

  • How would you handle follow-up questions in a RAG chatbot?
  • When is query decomposition worth it?
  • How do you stop a rewrite from changing the user's intent?
Interview tip: Mention keeping the original query and measuring by query type. That shows you treat rewriting as a tested component, not magic.
Loading hands-on exercise

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Query Rewriting with generative AI interview Q&A and hands-on practice.

Open Generative AI Q&A →Tech Learn Q&A
Previous topic
Reranking
Next topic
HyDE