A short user question transforming into several rewritten queries and a hypothetical answer before searching an index

Query Rewriting and HyDE for Better RAG Retrieval

Nobody types a query the way a document is written. The knowledge base says “Reset multi-factor authentication for a locked account.” The user types “cant login after phone swap.” Same intent, almost no shared words, and an embedding model has to bridge the gap with whatever it learned in training. Sometimes it does. Often it hands you the password-policy page and a cheerful shrug.

Query rewriting changes the user’s question into something your retriever handles better. HyDE (Hypothetical Document Embeddings) is one specific rewriting trick: have an LLM write a fake answer, then search with the embedding of that fake answer instead of the question. Both attack the same weak spot: the mismatch between how people ask and how corpora are written. This article sorts the techniques by the job they do, shows when each backfires, and gives you a way to prove they help before they cost you latency.

The vocabulary gap, in plain terms

Dense retrieval compares a query vector with passage vectors. Questions and answers are different kinds of text: a question is short, often incomplete, sometimes conversational; the answer passage is long, formal and full of domain terms. If you want a refresher on why vector closeness reflects meaning at all, see what embeddings are in AI. The key point here is that nearness is learned from training data, and your users’ phrasing may sit outside it.

Three symptoms point at this problem rather than at chunking or the vector store: the right document exists but ranks below 20, rewording the question by hand makes it appear, and failures cluster around short or follow-up queries. If instead the right text is split across chunks, go to chunking first.

Four jobs a rewrite can do

1. Make follow-ups standalone

In a chat, the user writes “what about for contractors?” The retriever has no idea what “what about” refers to. Condense the conversation into a self-contained query: “What is the parental leave policy for contractors?” This is the highest-value rewrite for any multi-turn assistant, and the least controversial. Give the rewriter only the last few turns, and tell it to preserve names, numbers and error codes exactly.

2. Normalize and expand

Turn “cant login after phone swap” into a cleaner statement and maybe a second variant: “reset two-factor authentication after replacing a phone.” Search both and merge. Expansion is where you can inject known synonyms from your own glossary, which is often more reliable than asking a model to guess company jargon.

3. Decompose compound questions

“Compare the SLA for the Pro and Enterprise plans and tell me which includes phone support” is really three retrievals. Splitting into sub-queries, retrieving separately and combining gives each part a fair shot. The research on rewriting queries for retrieval-augmented LLMs frames rewriting as a learned step in the pipeline rather than a fixed prompt, which is worth knowing even if you start with a plain prompt.

4. Shift to document style (HyDE)

When the query is short and abstract, ask a model to draft a passage that would answer it, then embed that draft. The draft is closer in style to real documents than the question was.

How HyDE works, and why wrong facts can still help

The idea comes from the paper Precise Zero-Shot Dense Retrieval without Relevance Labels. The pipeline is short:

  1. Send the query to an instruction-following LLM with a prompt like “write a short passage that answers this question.”
  2. Embed the generated passage (or several samples) with the same encoder you use for documents.
  3. Search the index using that vector and return real documents.

The generated passage may contain invented details. That sounds fatal, but the retrieval encoder acts as a filter: it maps the passage to a neighborhood of real documents, and details that match nothing real simply contribute noise rather than being quoted. The real passages then ground the final answer. The key is that the fake text is only used to find things; it never reaches the user.

A minimal sketch looks like this.

def hyde_search(query, llm, embed, index, k=20):
    draft = llm(f"Write a short factual passage answering: {query}")
    vec = embed(draft)
    return index.search(vec, k=k)

def multi_query_search(query, llm, embed, index, k=20):
    variants = [query] + llm_rewrites(query, n=2)
    lists = [index.search(embed(v), k=k) for v in variants]
    return reciprocal_rank_fusion(lists)[:k]

Notice the second function. Treat HyDE as one more variant to fuse, not a replacement for the original query. Keeping the raw query in the mix protects exact identifiers that a hypothetical passage would blur.

When HyDE and rewriting backfire

  • Rare identifiers. A query like “ERR_4471 on firmware 3.2.1” has little to paraphrase. A rewrite can drop or alter the code. Preserve tokens that look like IDs and lean on hybrid search for these.
  • Private knowledge the model lacks. If the topic is your internal product, the model’s fake answer will be generic and may point toward the wrong neighborhood. HyDE helps most when the model knows the domain well enough to write something plausible.
  • Ambiguity resolved wrongly. “Python 3 support” could mean the language or an SDK. A rewrite that guesses one meaning silently removes the other. When confidence is low, ask the user a clarifying question instead of rewriting.
  • Over-expansion. Five variants times 30 results floods the candidate pool with near-duplicates. Dedupe, fuse, and cap.
  • Latency you did not budget. An extra LLM call before retrieval can add noticeable delay. Use a small, fast model for rewriting and run variant searches in parallel.

Route instead of rewriting everything

Not every query deserves a rewrite. A cheap router can decide per request.

Query signalActionReason
Contains ID, code or quoted phraseSearch raw query, hybrid modeExact tokens matter.
Follow-up pronoun or fragment in a chatMake standaloneMissing context.
Short, abstract, concept-style questionAdd HyDE variantStyle mismatch likely.
Multiple asks joined by “and” or “compare”DecomposeSeparate evidence needed.
Long, specific, well-formed questionNo rewriteLittle to gain; save latency.

Start the router as simple rules and a log. Review the log weekly: which route did each query take, did retrieval succeed, did the rewrite change anything? The first month’s log will show you which rules deserve a model and which can stay rules. This is the sort of per-request decision logic that an agent harness is built to hold in one place.

Prompting the rewriter well

A rewrite prompt is a small contract. Specify the output format (JSON list of queries), the number of variants, what to preserve (numbers, product names, quoted strings, error codes), and what not to do (do not answer the question, do not add facts). Include two or three examples from your own logs, including one where the correct action is to return the query unchanged. Teaching the model to leave things alone prevents most over-rewriting. More on structuring instructions like this is in the prompt engineering guide.

Prove it helps: a paired test

Rewrites feel like improvements, so teams skip measurement. Do not. Collect 60 to 100 real queries, ideally with the document that should answer each one. Use real phrasing, typos included, rather than questions polished by an engineer.

  1. Run baseline retrieval and record whether the correct document lands in the top 5 and top 20.
  2. Run each technique (standalone rewrite, multi-query, HyDE) as a separate arm with the same index.
  3. Compare per query, not only on average. List queries where an arm improved and queries where it got worse.
  4. Cluster the losses. If HyDE hurts identifier queries, add a routing rule instead of discarding HyDE.
  5. Check added latency per arm and the share of requests that trigger it.

Averages hide the story here. A technique that wins 30 queries and loses 12 can be excellent with routing and mediocre without it. Pair this with answer-level checks from the RAGAS guide and, if you rerank after fusion, remember a reranker can rescue some rewriting misses while hiding others, so test with and without it.

Where this sits in the bigger picture

Rewriting is a pre-retrieval upgrade. It belongs in the same family as the improvements discussed in naive RAG vs advanced RAG, and it competes for engineering time with other fixes. If your failures are about missing knowledge rather than missed retrieval, RAG vs fine-tuning vs agents is the better next read. Embedding model choice and index design, covered in vector databases for AI, also shape how much any rewrite can help.

Frequently asked questions

What is query rewriting in RAG?
It is a step that transforms the user’s raw question into one or more queries better suited to your retriever, for example by adding missing context from a chat, fixing vocabulary, splitting compound questions, or generating a hypothetical answer.

What is HyDE in simple terms?
HyDE stands for Hypothetical Document Embeddings. An LLM writes a fake passage that would answer the query, and you search the index using that passage’s embedding instead of the question’s. Real documents are retrieved and used for the final answer.

Does HyDE work if the model writes incorrect facts?
Often yes, because the passage is only used to find similar real documents through the embedding model. Wrong details tend to match nothing and add noise rather than appearing in the answer. It works worse when the model lacks the domain knowledge to write anything plausible.

When should I not use query rewriting?
Skip it for queries with exact identifiers, quotes or error codes, and for long, already specific questions. Rewriting can alter those tokens or add latency without any benefit, so route such queries to raw or hybrid search.

Should I replace the original query with the rewrite?
Usually not. Keep the original as one of several variants and merge the result lists with a method such as reciprocal rank fusion. This protects exact terms and gives you a safety net when a rewrite goes wrong.

How many query variants are enough?
Two or three is a sensible starting point. More variants add cost and near-duplicate results. Test one arm per technique on real queries and keep only the variants that improve recall without unacceptable latency.

Related reading

About Mudasir Syed

Check Also

AI Agent Evaluation and Observability Guide — professional topic photo

AI Agent Evaluation and Observability Guide

AI agent evaluation: practical guide with definitions, implementation checklist, security notes, and internal links across the agentic stack.

Leave a Reply