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, and that you can call an LLM with a text prompt. Examples are in Python.
The core idea
Query rewriting means changing the user's question before it reaches the search index. The user's wording is written for a person. The index needs wording that matches how documents are written. A rewriting step sits between the two and translates.
The retriever and the generator stay the same. Only the text sent to the retriever changes. That makes rewriting a cheap place to fix retrieval problems, because you do not re-embed documents or retrain anything.
Where it sits in the pipeline
Rewriting runs after the user submits a question and before the search call. Some techniques also add a step after search, such as merging several result lists.
The rewrite stage can return one query or many. If it returns many, you search once per query and merge the ranked lists into one.
A family of techniques
Each technique targets a different failure from the previous chapter. The later chapters cover them in detail. This table is the map.
| Technique | What it does | Failure it targets |
|---|---|---|
| Conversational condensing | Turns a follow-up into a standalone question | Missing conversation context |
| Multi-query expansion | Searches several phrasings and merges results | Vocabulary mismatch |
| HyDE | Searches with a hypothetical answer | Short query, long documents |
| Step-back | Asks a broader question first | Question too specific |
| Decomposition | Splits a question into sub-questions | Multi-part questions |
A minimal rewriter
Every technique has the same shape: build a prompt, call the model, parse the reply. This version rewrites a question into a keyword-style query. The llm argument is any function that takes a prompt string and returns a string, so you can plug in your own client.
from typing import Callable
def rewrite_query(question: str, llm: Callable[[str], str]) -> str:
prompt = (
"Rewrite the question below as a short search query. "
"Use the terms a technical document would use. "
"Keep all names, numbers and constraints. "
"Return only the query.\n\n"
f"{question}"
)
rewritten = llm(prompt).strip()
return rewritten or question
def fake_llm(prompt: str) -> str:
return "PostgreSQL connection pool size configuration"
print(rewrite_query("how many db connections can my app open?", fake_llm))Note the last line of rewrite_query. If the model returns an empty string, the function falls back to the original question. A rewriter should never leave you with nothing to search.
Common errors
- Dropping constraints. The model removes a date, product name or version. The query then retrieves general material. Tell the prompt to keep names, numbers and constraints.
- Rewriting when you should not. A clear, specific question can get worse after rewriting. Compare against the raw query before you keep a rewriter.
- Replacing the question instead of adding to it. Searching with the original and the rewrite together is safer than searching with the rewrite alone.
- Sending the rewrite to the generator. Usually the generator should answer the user's original question. The rewrite is for search only.
- Chatty output. Models sometimes add "Here is the query:". Ask for the query only, and strip whitespace.
Choosing a starting point
Look at your failed queries first. If they are follow-ups, start with condensing. If the right document exists but uses different words, try multi-query expansion. If questions have several parts, try decomposition. Add one technique at a time so you can tell which one helped.
Exercise
A user asks "and how much does it cost?" after a chat about a product. A rewriter that sees only that message returns it unchanged. Which stage fails, and what input does the rewriter need?
Show answer
Retrieval fails because the query has no subject, so nothing in the index matches it. The rewriter needs the conversation history so it can produce a standalone question such as "How much does the product cost?".