โ† Back to Blog
RAGAI EngineeringLLMs

RAG Query Transformation: Rewriting, Multi-Query, HyDE and Step-Back Prompting in Production

Your retriever is only as good as the query it receives, and users write terrible queries. Learn when query rewriting, multi-query fan-out, HyDE and step-back prompting actually lift recall, and when they just add latency.

By Joinloopยท23 October 2026ยท7 min read
ShareLinkedInXReddit
๐Ÿ”Ž

You tuned your chunking. You added a reranker. You switched embedding models. Recall is still mediocre, and when you read the failing traces the cause is obvious: the user asked something the index can't match.

"what about the refund thing for the annual one?" is not a query. It is a fragment of a conversation. Embedding it and running nearest-neighbour search gives you whatever chunk happens to sit closest to a vague vector. Query transformation fixes the input to retrieval instead of the retrieval itself, and it is often the cheapest recall gain left once the basics are in place.

Why raw user queries fail

Four failure modes show up repeatedly in production traces:

  1. Context dependence. Follow-up turns ("and for enterprise?") only make sense with chat history.
  2. Vocabulary mismatch. The user says "cancel", the docs say "terminate subscription".
  3. Query/document asymmetry. Questions are short and interrogative. Documents are long and declarative. Their embeddings don't always land near each other.
  4. Compound or too-specific questions. One query that needs facts from three places, or one so narrow that the answer lives in a broader passage.

Each transformation technique targets one or more of these.

The four techniques

1. Conversational rewriting (standalone query)

Rewrite the latest message into a self-contained query using chat history. This is the highest-value, lowest-risk technique. If you build chat RAG and do nothing else, do this.

from openai import OpenAI

client = OpenAI()

REWRITE_PROMPT = """Rewrite the user's last message as a standalone search query.
- Resolve pronouns and references using the conversation.
- Keep product names, numbers and identifiers exactly.
- Do not answer the question. Output only the query."""

def rewrite(history: list[dict], question: str) -> str:
    convo = "\n".join(f"{m['role']}: {m['content']}" for m in history[-6:])
    resp = client.chat.completions.create(
        model="gpt-4o-mini",  # any small, fast model works; check current model names
        temperature=0,
        messages=[
            {"role": "system", "content": REWRITE_PROMPT},
            {"role": "user", "content": f"Conversation:\n{convo}\n\nLast message: {question}"},
        ],
    )
    return resp.choices[0].message.content.strip()

Keep only the last few turns. Feeding the whole history adds latency and invites the rewriter to drag in stale topics.

2. Multi-query fan-out

Generate N paraphrases or sub-questions, retrieve for each, then merge results. This attacks vocabulary mismatch and compound questions. Merge with Reciprocal Rank Fusion (RRF) rather than raw scores, because scores from different queries aren't comparable.

from collections import defaultdict
import json

def expand(query: str, n: int = 3) -> list[str]:
    resp = client.chat.completions.create(
        model="gpt-4o-mini",
        temperature=0.4,
        response_format={"type": "json_object"},
        messages=[{
            "role": "user",
            "content": (
                f"Generate {n} alternative search queries for: {query!r}. "
                "Vary vocabulary and, if the question is compound, split it. "
                'Return JSON: {"queries": [...]}'
            ),
        }],
    )
    return json.loads(resp.choices[0].message.content)["queries"]

def rrf(result_lists: list[list[str]], k: int = 60) -> list[str]:
    scores = defaultdict(float)
    for results in result_lists:
        for rank, doc_id in enumerate(results):
            scores[doc_id] += 1.0 / (k + rank + 1)
    return sorted(scores, key=scores.get, reverse=True)

def retrieve_multi(query: str, search, top_k: int = 20) -> list[str]:
    queries = [query] + expand(query)
    lists = [search(q, top_k) for q in queries]  # run these in parallel in prod
    return rrf(lists)[:top_k]

Always include the original query in the set. Run the searches concurrently, so the added latency is one LLM call plus the slowest search, not N searches in sequence.

3. HyDE (Hypothetical Document Embeddings)

Ask the model to write a plausible answer, then embed that instead of the question. The fake answer is declarative and vocabulary-rich, so it sits closer to real documents in embedding space. The details of the hallucinated answer don't need to be right, only its shape and terminology.

def hyde(query: str) -> str:
    resp = client.chat.completions.create(
        model="gpt-4o-mini",
        temperature=0.2,
        messages=[{
            "role": "user",
            "content": f"Write a short passage (3-4 sentences) that would answer: {query}\n"
                       "It is fine if details are guessed; match the style of technical documentation.",
        }],
    )
    return resp.choices[0].message.content

def retrieve_hyde(query: str, embed, vector_search, top_k: int = 20):
    return vector_search(embed(hyde(query)), top_k)

HyDE shines on short, abstract queries against dense technical corpora. It can hurt when the query contains a precise identifier (an error code, SKU or function name), because the hypothetical answer may drop or distort it. Hybrid search with BM25 on the original query protects you there.

4. Step-back prompting

Generate a more general question and retrieve for both. "Why does my pgvector HNSW index return fewer than k rows with a filter?" steps back to "How does filtering interact with HNSW search in pgvector?" The broader query pulls conceptual passages, while the original pulls specifics. Feed both sets to the generator.

Which one to use

Technique Fixes Extra cost Main risk Use when
Conversational rewrite Context dependence 1 small LLM call Rewriter adds or drops facts Any multi-turn chat
Multi-query + RRF Vocabulary mismatch, compound questions 1 LLM call + N searches Noise from weak paraphrases; Nร— retrieval load Recall is low, queries are ambiguous
HyDE Query/document asymmetry 1 LLM call (longer output) Distorts exact identifiers Short abstract queries, technical prose
Step-back Over-specific queries 1 LLM call + 1 search Broad chunks crowd out specifics "Why does X happen" questions

A sensible default pipeline: rewrite โ†’ (original + 2 paraphrases) โ†’ hybrid search โ†’ RRF โ†’ rerank. Add HyDE or step-back only if your evaluation shows a specific failure class they fix.

Measure before you ship

Query transformation adds an LLM call to every request, so it must earn its latency. Build a golden set of real queries with known relevant chunks and compare variants on recall@k and MRR, split by query type. If you don't have this yet, our guide on RAG retrieval evaluation with golden sets walks through it.

A minimal harness:

def recall_at_k(retrieve, dataset, k=10):
    hits = 0
    for q, relevant_ids in dataset:
        got = set(retrieve(q)[:k])
        hits += bool(got & set(relevant_ids))
    return hits / len(dataset)

variants = {
    "baseline": lambda q: search(q, 20),
    "multi_query": lambda q: retrieve_multi(q, search),
    "hyde": lambda q: retrieve_hyde(q, embed, vector_search),
}
for name, fn in variants.items():
    print(name, recall_at_k(fn, golden_set))

Report results per segment (short vs long queries, identifier-heavy vs natural language, first turn vs follow-up). Averages hide the fact that HyDE might help one segment and hurt another.

Common pitfalls

  • Rewriting without guardrails. A rewriter told to "improve" the query will invent constraints. Instruct it to preserve identifiers and never answer.
  • Dropping the original query. Always keep it in the candidate set. Transformations are additive.
  • Averaging scores across queries. Use RRF or rerank the merged pool with a cross-encoder.
  • Sequential fan-out. Parallelise searches, or the p95 latency climbs fast.
  • Using a big model for the rewrite. A small, fast model at temperature 0 is usually enough. The rewrite sits on the critical path.
  • Skipping the cache. Rewritten queries repeat. Cache transformations keyed on the normalized input, as you would with a semantic cache.
  • No fallback. If the transformation call times out, fall through to the raw query rather than failing the request.
  • Evaluating on synthetic queries only. Real users write messier input than an LLM-generated test set. Mine real traces where you can.

Checklist

  • Follow-up turns are rewritten into standalone queries
  • Original query always included alongside transformed ones
  • Results merged with RRF, then reranked
  • Transformation model is small, deterministic and has a timeout with fallback
  • Recall@k and MRR measured per query segment before and after
  • Added p50/p95 latency and per-request cost are tracked
  • Exact-identifier queries still hit a lexical (BM25) path

Next steps

Start with conversational rewriting, measure it, then try multi-query on the segments where recall is weakest. Treat HyDE and step-back as targeted tools, not defaults. Check your provider's current docs for model names and parameters, since those change often.

If you want to build and evaluate full RAG systems with feedback from practitioners, our engineering cohort covers retrieval, evals and production concerns hands-on. Take a look at the Joinloop cohort.

ShareLinkedInXReddit

Want to build this yourself?

Join a live cohort and go from reading about AI to shipping it, with practitioners who do it daily.