Sub topic 3
Query rewriting: the core idea and where it sits in the pipeline
This chapter assumes you have built a basic RAG pipeline (index, retrieve, generate). It also assumes you know what embeddings and BM25 keyword search do, can call a language model with a text prompt, and can read Python. The chapter explains what query rewriting is and where it fits in a pipeline. Later chapters cover each technique in detail.
The core idea
A retrieval system compares a query to documents. The user's question is written for a person, so it is often a poor query for a search index. Query rewriting inserts a step between the user and the index. That step turns the question into one or more queries that the index can answer better.
The rewriting step is usually a call to a language model (LLM). It can also be a rule or a small trained model. The goal is the same in every case: change what you search with, not what you search in. The documents, the index, and the embedding model stay as they are.
This is why query rewriting is a popular first fix. You can add it without re-indexing, and you can remove it just as easily.
Where it sits in the pipeline
A single-shot RAG pipeline has four stages: take the question, retrieve the top-k passages, build a prompt, generate an answer. Query rewriting sits between the first two stages.
Three points about this layout matter in practice.
- The generator still answers the user's original question. The rewritten queries are only used for search. If you hand the rewritten text to the generator as if the user had written it, you can change the meaning of the question without noticing.
- The rewriting step can produce many queries. When it does, you need a merge step to combine the ranked lists. Reciprocal rank fusion, covered in a later chapter, is the usual choice.
- Rewriting can run more than once. In multi-step retrieval, results from one search shape the next query. The pipeline then becomes a loop instead of a line.
What a rewriting step can do
Rewriting techniques differ in what they output, and the output tells you which failure each one targets. The table gives a preview. Each row has its own chapter.
| Technique | What it produces | Failure it targets |
|---|---|---|
| Conversational rewriting | One standalone query | The question depends on earlier turns |
| Multi-query expansion | Several phrasings of the same question | The user's words differ from the document's words |
| HyDE | A hypothetical answer used as the query | A short question is far from long answer passages in embedding space |
| Step-back | A broader, more general question | The question is too specific for the documents |
| Decomposition | Several sub-questions | One question needs facts from several places |
| Routing | A choice of strategy, or no retrieval | Not every question needs the same treatment |
Notice that the techniques fall into three shapes. Some map one query to one query. Some map one query to many queries that you then search and merge. Some run search and rewriting in turns. Knowing the shape tells you what code you need around it.
A minimal wrapper
A good way to keep rewriting manageable is to give every rewriting technique the same interface. It takes a question and returns a list of queries. The pipeline then does not care which technique it uses.
The following example is complete and runs as shown. It uses a stand-in function in place of a real model and a tiny in-memory search so that you can see the structure. You would replace both with your real components.
from typing import Callable
Rewriter = Callable[[str], list[str]]
def identity_rewriter(question: str) -> list[str]:
"""No rewriting: the baseline every other rewriter is compared against."""
return [question]
def lowercase_split_rewriter(question: str) -> list[str]:
"""A toy rewriter: the original plus a keyword-only variant."""
stop = {"what", "is", "the", "a", "an", "of", "how", "do", "i", "to"}
keywords = [w for w in question.lower().strip("?").split() if w not in stop]
return [question, " ".join(keywords)]
DOCS = {
"d1": "reset your password from the account settings page",
"d2": "billing invoices are sent on the first of each month",
"d3": "to change a password open settings and choose security",
}
def search(query: str, top_k: int) -> list[str]:
"""Rank documents by how many query words they contain."""
words = set(query.lower().strip("?").split())
scored = []
for doc_id, text in DOCS.items():
overlap = len(words & set(text.split()))
if overlap:
scored.append((overlap, doc_id))
scored.sort(reverse=True)
return [doc_id for _, doc_id in scored[:top_k]]
def retrieve(question: str, rewriter: Rewriter, top_k: int = 2) -> list[str]:
seen: list[str] = []
for query in rewriter(question):
for doc_id in search(query, top_k):
if doc_id not in seen:
seen.append(doc_id)
return seen[:top_k]
question = "How do I change the password?"
print(retrieve(question, identity_rewriter))
print(retrieve(question, lowercase_split_rewriter))The retrieve function here simply concatenates results and removes duplicates. That is enough to show the structure, but it throws away rank information. Real multi-query pipelines should merge with reciprocal rank fusion instead.
The important design choice is the Rewriter type. Because every technique returns list[str], you can swap them, chain them, or compare them in an evaluation. The identity_rewriter is not a joke. It is the baseline. If you cannot show that a rewriter beats it, you should not ship the rewriter.
Choosing where rewriting happens
Rewriting can sit in different places, and each has costs.
- Before retrieval, on every request. This is the default. It is simple, and it adds one LLM call of latency before any search starts.
- Only when a check says it is needed. A cheap test, such as "does the question contain a pronoun like it or that?" or a routing step, decides whether to rewrite. This saves cost but adds a decision that can be wrong.
- Offline, at index time. Instead of rewriting queries, you enrich documents, for example by generating likely questions for each passage. This is the mirror image of query rewriting. It moves the cost out of the request path, but it needs re-indexing whenever you change it. This chapter does not cover it further.
Most systems start with option 1 for the techniques they need, then move to option 2 once they have measured which questions benefit.
Choosing the model for rewriting
The rewriting step is a short task: a few lines in, a few lines out. A small, fast model is often enough. Using your largest model here adds latency to every request for little gain. Keep these points in mind:
- Set the temperature low for single-query rewrites, so the same question gives the same query. This makes caching and debugging easier.
- Allow more variety for multi-query expansion, since you want different phrasings. You can still keep the number of variants small.
- Ask for a strict output format, such as one query per line with no numbering, and parse it defensively. Models add numbering and commentary despite instructions.
Common errors
These problems appear in almost every first implementation.
- Rewriting what did not need rewriting. A clear, self-contained question can get worse after a rewrite. The model may add words, drop a constraint, or generalize. Always keep the original question as one of the queries when you search with several.
- Losing names and constraints. A rewrite that turns "Does the Pro plan support SSO in the EU region?" into "Does the product support single sign-on?" loses two filters. Tell the model to keep every name, number, and constraint.
- Sending the rewrite to the generator. As noted above, the generator should see the original question, with the retrieved passages as context.
- No fallback. Model calls fail and time out. If rewriting fails, fall back to the original question so the user still gets an answer.
- No baseline. Without the identity rewriter as a comparison, you cannot tell whether a change helped.
Summary of the working model
Query rewriting changes the input to retrieval and leaves the index alone. Every technique maps a question to one or more queries, and some of them repeat the process in a loop. A shared interface makes techniques interchangeable and testable. The original question stays in the search set and goes to the generator. The next chapters cover specific techniques, starting with the conversational case.
Exercise
A teammate adds a rewriter that turns the user's question into a single cleaner query, then passes that rewritten query to both the retriever and the generator. Name two problems with this design and say how you would fix each.
Show answer
First, the generator now answers a question the user did not ask. A rewrite can drop a name, number, or constraint, so the answer may not match the user's intent. Fix this by giving the generator the original question and using the rewrite only for search. Second, the original question is no longer searched, so a bad rewrite can lose results that the raw query would have found. Fix this by keeping the original question in the set of queries, and merge the results (for example with reciprocal rank fusion). A fallback to the original question when the rewrite call fails, and a comparison against the identity rewriter in evaluation, also help.
Exercise
In the minimal wrapper, what does identity_rewriter do, and why is it kept in a real project?
Show answer
It returns the original question as the only query, so it performs no rewriting. It is the baseline. Any real rewriter must retrieve better than it on your evaluation questions to justify the extra latency and cost.