Query transformation for RAG: multi-query, HyDE, step-back, decomposition and routing
Users rarely phrase questions the way documents are written. Query transformation rewrites, expands or splits the question before retrieval. This guide explains multi-query, HyDE, step-back, decomposition and routing, runs them on a small corpus, and prices the extra calls.
- Reading time
- 14 min
- Sections
- 7
- Code examples
- 2
- Tables
- 3
- Sources
- 8
- Published
- 24 Nov 2026
- What changed
- Haystack 3.5.0 ships a QueryExpander component
- Why it matters
- Query transformation is a recall tool.
- What to do
- Collect real user questions
A retrieval-augmented generation (RAG) system can only find what the question points at. People ask "How many holidays do I get, and can I keep the ones I don't use?" while the HR handbook says "annual leave", "accrue" and "carried over". Keyword search finds nothing; dense search may find something close but not both halves of the answer. The failure is not in the index or the model. It is in the query.
Query transformation is the family of techniques that change the question before retrieval: rewriting it, expanding it into several versions, imagining an answer and searching with that, stepping back to a more general question, splitting it into parts, or routing it to the right source. Two major RAG frameworks shipped releases this month that package these steps as standard components. This article explains each technique, runs four of them on a small corpus with runnable code, and prices the extra model calls they add.
An analogy: a good reference librarian does not search for your exact words. They ask what you really mean, try the official terms, split a two-part question into two searches, and know which shelf or database to check first. Query transformation teaches a RAG pipeline those habits.
What happened
Haystack 3.5.0 ships a QueryExpander component (10 November 2026)
Haystack, deepset's open-source RAG framework, released 3.5.0 on PyPI on 10 November 2026. The installed package includes QueryExpander in haystack.components.query. It asks a chat model to return a JSON object with a queries array of semantically similar rewrites. The defaults are n_expansions=4 and include_original_query=True, and the built-in prompt tells the model to use different words, synonyms and related terms, keep the same intent, favour variations that work well with keyword search, and answer in the language of the input. The same release includes routers such as ConditionalRouter, MetadataRouter and LLMMessagesRouter for sending queries down different paths.
LangChain Classic 1.1.0 keeps MultiQueryRetriever (23 November 2026)
LangChain Classic, the package that holds LangChain's pre-1.0 chains and retrievers, released 1.1.0 on 23 November 2026, while the main langchain package reached 1.5.2 on 18 November. Classic 1.1.0 still includes MultiQueryRetriever in langchain_classic.retrievers.multi_query. Its default prompt asks the model "to generate 3 different versions of the given user question to retrieve relevant documents from a vector database", to "overcome some of the limitations of distance-based similarity search". The package also keeps a self-query retriever, which turns parts of a question into metadata filters, and a re-phrasing retriever.
Six ways to transform a query
| Technique | What it does | Best for | Extra cost |
|---|---|---|---|
| Rewriting | One cleaner query: fix typos, resolve "it" from chat history, use domain terms | Conversational RAG, sloppy queries | 1 small LLM call |
| Multi-query | Several paraphrases, retrieve for each, fuse results | Vocabulary mismatch, ambiguous wording | 1 LLM call, n retrievals |
| HyDE | Write a hypothetical answer, search with its text or embedding | Short questions against long, formal documents | 1 LLM call with longer output |
| Step-back | Ask a more general question first, retrieve background too | Questions needing principles or context | 1 LLM call, 2 retrievals |
| Decomposition | Split a multi-part or multi-hop question into sub-questions | Comparisons, "and" questions, multi-hop facts | 1 LLM call, one retrieval per part, sometimes sequential |
| Routing | Pick the index, tool or pipeline for the question | Several sources, or easy versus hard questions | 1 classifier or LLM call |
Rewriting and multi-query
Query rewriting turns a raw user message into a good search query. In a chat, "what about for contractors?" means nothing without the previous turn; a rewrite step produces "annual leave entitlement for contractors". Multi-query goes further: generate several versions with different words, run retrieval for each, and fuse the ranked lists, usually with reciprocal rank fusion (RRF). Each variant has a chance to hit vocabulary the others miss. The multi-query RAG simulation shows the fan-out and fusion.
HyDE: search with an imagined answer
Hypothetical Document Embeddings (HyDE), from Gao and colleagues (arXiv 2212.10496), asks a language model to write a plausible answer to the question, then embeds that answer and searches with it. The idea is that a fake answer looks more like the real answer passage than the question does: it uses the same register, terms and length. The hypothetical document may contain wrong facts, but that does not matter for retrieval; only the real retrieved passages reach the final prompt. The site's HyDE page and HyDE simulation walk through it.
Step-back prompting
Step-back prompting, from Zheng and colleagues at Google DeepMind (arXiv 2310.06117), asks the model to first pose a more abstract question. For "Why did my heat pump's efficiency drop in January?", the step-back question might be "How does outdoor temperature affect heat pump efficiency?". Retrieving for both gives the model the principle and the specific facts.
Decomposition
Some questions are really two or more questions. "Compare the parental leave and sick leave rules" needs two retrievals. Multi-hop questions, such as "Who manages the team that owns the billing service?", need the answer to one part before the next can be asked, so retrieval becomes a short sequence. This is where query transformation shades into agentic RAG.
Routing
Routing chooses where a question goes: the HR index or the engineering wiki, a SQL tool or vector search, a cheap single-shot pipeline or an expensive multi-step one. Adaptive-RAG (Jeong and colleagues, arXiv 2403.14403) trains a small classifier to predict question complexity and picks between no retrieval, single-step and multi-step retrieval accordingly. The site's LLM routing page covers routing between models, which uses the same pattern.
Running the techniques on a small corpus
The script uses BM25 keyword search over six HR policy sentences. The question uses everyday words that appear in none of them. To keep the example runnable without an API key, the rewrites and the hypothetical answer are written as an LLM would plausibly produce them; in production they come from a model call through Haystack's QueryExpander, LangChain's MultiQueryRetriever or your own prompt. Install with pip install rank_bm25.
from rank_bm25 import BM25Okapi
docs = [
"Employees accrue 2.5 days of annual leave per month worked.",
"Unused vacation days can be carried over until 31 March.",
"Parental leave is 16 weeks at full pay for the primary carer.",
"Expense claims must be filed within 30 days with receipts.",
"Remote work requires a signed equipment agreement.",
"Sick leave requires a doctor's note after three consecutive days.",
]
STOP = {"how", "many", "do", "i", "get", "a", "the", "can", "my", "of", "per", "is",
"to", "what", "if", "in", "be", "until", "at", "for", "with"}
tok = lambda s: [w for w in s.lower().replace(".", " ").replace("?", " ")
.replace("'", " ").split() if w not in STOP]
bm = BM25Okapi([tok(d) for d in docs])
def rank(q): # only documents that match at all
sc = bm.get_scores(tok(q))
return [i for i in sorted(range(len(docs)), key=lambda i: -sc[i]) if sc[i] > 0]
def rrf(lists, k=60):
s = {}
for r in lists:
for p, d in enumerate(r, 1):
s[d] = s.get(d, 0) + 1 / (k + p)
return sorted(s, key=lambda d: -s[d])
question = "How many holidays do I get, and can I keep the ones I don't use?"
relevant = {0, 1}
variants = ["annual leave entitlement days per month", "carry over unused vacation days"]
hyde = ("Employees accrue days of annual leave each month; "
"unused vacation days can be carried over.")
def show(name, r): print(name, r[:3], len(set(r[:2]) & relevant) / 2)
show("original", rank(question))
show("multi-query", rrf([rank(question)] + [rank(v) for v in variants]))
show("decomposed", rrf([rank(v) for v in variants]))
show("HyDE", rank(hyde))
| Method | Top 3 results | Recall@2 |
|---|---|---|
| Original question | none match | 0.0 |
| Multi-query (original plus 2 variants, RRF) | 1, 0, 3 | 1.0 |
| Decomposition (one sub-query per part, RRF) | 1, 0, 3 | 1.0 |
| HyDE (search with hypothetical answer) | 1, 0, 3 | 1.0 |
The original question scores zero against every document: "holidays", "keep" and "use" appear nowhere, and the remaining words are stopwords. Each transformation fixes the vocabulary gap and finds both relevant sentences, the accrual rule and the carry-over rule. The third result, the expense-claims sentence, comes in only because it shares the word "days", which shows the side effect of expansion: more matches, including weak ones. A reranker after fusion removes most of that noise.
A dense retriever would have done better than BM25 on the original question, because it matches meaning. But the same pattern holds in dense search on harder cases: paraphrases and hypothetical answers move the query vector towards the region where answer passages live, and fusion rewards documents that several versions agree on.
Pricing the extra steps
Every transformation adds at least one model call before retrieval, and that call sits on the critical path of the answer.
| Technique | Extra LLM calls | Extra output tokens (typical) | Extra retrievals |
|---|---|---|---|
| Rewrite | 1 | 20 to 40 | 0 |
| Multi-query, n = 4 | 1 | 60 to 120 | 4 |
| HyDE | 1 | 100 to 200 | 0 (one search with the fake answer) |
| Step-back | 1 | 20 to 40 | 1 |
| Decomposition, 3 parts | 1 (plus 1 per hop if sequential) | 40 to 100 | 3 |
| Routing | 1 small call or a classifier | under 10 | 0 |
Two rules follow. First, output tokens drive latency: a model generating 150 tokens of hypothetical answer at 100 tokens per second adds 1.5 seconds, while a 30-token rewrite adds 0.3 seconds. Use a small, fast model for transformation. Second, retrievals are cheap but fan-out multiplies reranking cost: four queries times 25 candidates is up to 100 candidates to rerank, so deduplicate after fusion and rerank only the top of the fused list.
The cheapest win is often conditional transformation: route easy, well-formed queries straight to retrieval, and transform only when the first retrieval looks weak (for example, low top score or few matches). That is the logic behind Adaptive-RAG and, in its more general form, corrective and agentic RAG.
Continue learning
How this article connects
7 pages link to or from it. Drag to turn, click a dot to open it.
What it means in practice
Query transformation is a recall tool. It helps most when users and documents speak different vocabularies, when questions have several parts, and in chat, where follow-up questions depend on earlier turns. It helps least when queries are already precise, such as an error code, where rewriting can even hurt by drifting from the exact string. Keeping the original query in the fused set, which Haystack's include_original_query=True does by default, protects against that drift.
The framework releases this month make the technique a configuration choice rather than custom code. That is useful, but the defaults deserve attention: four expansions means four retrievals and a larger reranking pool for every question. Pair transformation with hybrid search and a reranker, and measure on questions that reflect how your users really write.
Routing deserves more attention than it gets. A system with several sources, such as documents, a database and the web, wastes money and accuracy when it searches all of them for every question. A small router in front of retrieval can cut cost and improve precision at the same time. Prompt and pipeline optimisers such as DSPy can tune rewrite prompts against a metric instead of by hand.
What to do now
- Collect real user questions. Transformation fixes the gap between how people ask and how documents are written; you need real phrasing to see that gap.
- Add a rewrite step for chat. Resolve pronouns and follow-ups from history into a standalone query before retrieval.
- Try multi-query with RRF on vocabulary-mismatch failures. Start with three or four variants and keep the original query in the fused set.
- Test HyDE on short questions against long, formal documents. Compare recall with and without it; drop it where it does not help.
- Decompose comparison and "and" questions. Retrieve per part, then give the model all parts' evidence with clear labels.
- Route before you retrieve when you have several sources. A small classifier or a cheap LLM call can pick the index or tool.
- Use a small, fast model for transformation. Output length drives latency; keep rewrites short and structured as JSON.
- Rerank after fan-out. Deduplicate fused results and rerank the top 20 to 50 to remove noise added by expansion.
- Transform only when needed. Trigger expansion when first-pass retrieval scores are weak, and measure the latency saved.
Risks and open questions
Rewrites can change the question. An LLM may "helpfully" narrow or broaden intent, or translate domain terms into the wrong ones. Keep the original query in the mix and log rewrites for review.
Exact strings can be lost. Paraphrasing an error code, a name or a legal citation can remove the very token that keyword search needed. Detect such tokens and pass them through unchanged.
HyDE can mislead on unfamiliar topics. If the model knows nothing about a private domain, its hypothetical answer may use the wrong vocabulary and pull retrieval off course.
Latency and cost compound. Transformation, fan-out retrieval and reranking each add time. Without conditional triggering, every question pays for the hardest case.
Evaluation is harder. More moving parts mean more ways to regress. Measure recall per technique on the same labelled set, and keep a "no transformation" baseline.
Watch next: whether framework defaults move towards conditional, router-driven transformation, and how well small models fine-tuned only for query rewriting compete with general LLMs on recall and latency.
Frequently asked questions
What is query transformation in RAG?
It is any step that changes the user's question before retrieval to improve what the search finds. Common forms are rewriting, multi-query expansion, HyDE, step-back questions, decomposition into sub-questions and routing to the right source.
Is HyDE better than multi-query?
They fix different problems. HyDE helps when short questions must match long, formal passages, because a hypothetical answer resembles them. Multi-query helps when the right words are uncertain, because several phrasings cover more vocabulary. Test both on your own questions.
Does query transformation slow down answers?
Yes, by at least one model call. A short rewrite with a small model adds a few hundred milliseconds; a long hypothetical answer can add more than a second. Triggering transformation only when first-pass retrieval is weak keeps the average cost low.
Should I keep the original query when expanding?
Usually yes. The original wording often contains exact terms that paraphrases drop. Haystack's QueryExpander includes the original by default, and fusing it with the variants protects against rewrites that drift.
What is the difference between decomposition and agentic RAG?
Decomposition splits a question into sub-questions in one planned step. Agentic RAG lets a model decide step by step whether to retrieve again, from where and with what query, based on what it has found. Decomposition is a fixed plan; agentic RAG adapts as it goes.
Summary
Query transformation closes the gap between how people ask and how documents are written. Rewriting cleans a single query, multi-query and decomposition run several searches and fuse them, HyDE searches with an imagined answer, step-back adds background, and routing sends each question to the right source. On a small HR corpus, the original question matched nothing with BM25, while multi-query, decomposition and HyDE each found both relevant passages, at the price of one extra model call and some added noise. Haystack 3.5.0 and LangChain Classic 1.1.0 package these steps as standard components this month. Use them with a small fast model, keep the original query, rerank after fan-out and transform only when first-pass retrieval looks weak.
Sources
- Code PyPI: haystack-ai release history
- Code GitHub: Haystack QueryExpander source
- Code PyPI: langchain-classic release history
- Code GitHub: LangChain MultiQueryRetriever source
- Paper arXiv: Precise Zero-Shot Dense Retrieval without Relevance Labels (Gao et al., HyDE)
- Paper arXiv: Take a Step Back: Evoking Reasoning via Abstraction in Large Language Models (Zheng et al.)
- Paper arXiv: Adaptive-RAG: Learning to Adapt Retrieval-Augmented LLMs through Question Complexity (Jeong et al.)
- Paper arXiv: Least-to-Most Prompting Enables Complex Reasoning in Large Language Models (Zhou et al.)
Cite this article
Kelahmet, Ö. C. (2026, November 24). Query transformation for RAG: multi-query, HyDE, step-back, decomposition and routing. Özer Cem KELAHMET. https://www.ozercemkelahmet.com/articles/query-transformation-multi-query-hyde-routing
BibTeX
@online{kelahmet2026query,
author = {Kelahmet, {\"O}zer Cem},
title = {{Query transformation for RAG: multi-query, HyDE, step-back, decomposition and routing}},
year = {2026},
month = {nov},
url = {https://www.ozercemkelahmet.com/articles/query-transformation-multi-query-hyde-routing}
}Version historyfirst version
- Published
Factual corrections are listed here with what changed. Wording and formatting edits are not listed.