Retrieval
Query rewriting for RAG: HyDE, multi-query and the user's words
Decide whether HyDE or multi-query rewriting helps your RAG retrieval, keep the user's original query in the search, and fuse the result lists so it is not buried.
By Rose Donaldson, Context Retrieval team · Published
This article was drafted with AI assistance from the sources listed below and edited and published by the Context Retrieval team.
- 1Measure the missesRun your golden questions and find the misses where the user's wording, not the index, is the problem.
- 2Keep the originalSearch with the original query as one of the queries. DMQR-RAG keeps it in its query set.
- 3Fuse, do not concatenateMerge the result lists with rank fusion, and give the original query's list more weight.
- 4Compare at your kRerun the set and compare against the original query alone before you keep the rewrite.
Users type short, vague questions, and a retriever takes them literally. Query rewriting puts a model between the two: it reformulates the question, or writes several versions of it, or drafts a hypothetical answer, and the retriever searches with the result. The pillar on retrieval for web-sourced RAG gives this one paragraph and a warning. This post goes further: what two studies found, what a common implementation does with the user's own words, and how to merge the result lists so those words still count.
Three kinds of rewrite
The techniques differ in what they hand to the retriever.
- HyDE (Hypothetical Document Embeddings) asks an instruction-following model to write a document that would answer the query, embeds that document, and retrieves the real documents nearest to it.1 The authors argue that the encoder's dense bottleneck filters out the false details the generated document contains, and report that HyDE significantly outperforms the unsupervised Contriever retriever and performs comparably to fine-tuned retrievers across their tasks.1
- Multi-query asks a model for several alternative questions, retrieves for each one separately and merges the results.2
- Typed rewrites generate different kinds of variant on purpose. DMQR-RAG defines four: General Query Rewriting refines the query and removes noise, Keyword Rewriting extracts key terms such as nouns and subjects, Pseudo-Answer Rewriting adds a generated answer, and Core Content Extraction drops superfluous detail.3
What the studies measured
ARAGOG compared RAG techniques on one corpus: 423 AI and LLM papers from the AI ArXiv collection, with 107 question-answer pairs generated by GPT-4 and reviewed by people, GPT-3.5-turbo as the model, and each technique run 10 times.2 Its primary metric was retrieval precision, the share of retrieved context an LLM evaluator judged relevant. HyDE significantly improved retrieval precision. Multi-query went the other way: the authors report a reduction in retrieval precision compared with naive RAG, call the result contrary to what they expected, and offer no confirmed explanation.2 They also list their limits: one dataset, 107 questions, different chunking across techniques, and no consensus on RAG metrics.2
DMQR-RAG is a multi-query method that came out ahead. With GPT-4 doing the rewriting, it reports top-5 precision of 62.43 against 53.62 for RAG-Fusion on AmbigNQ, a top-5 hit rate of 54.18 against 51.58 on HotpotQA, and accuracy of 76.67 against 74.50 on FreshQA.3 Not every number moved: exact match on AmbigNQ was slightly lower, 55.24 against 55.47.3 Relevance was judged by GPT-4, and the paper also tested Llama3-8B and Qwen2-7B as rewriters.3
These results do not contradict each other as much as they seem to. ARAGOG tested a generic multi-query setup on technical papers. DMQR-RAG tested rewrites with deliberately different information content, on open-domain question sets. Neither tested web documentation pages, so neither tells you what will happen on your index.
Keep the user's words in the search
One detail in DMQR-RAG matters more than its headline numbers: the original query stays in the set of queries used for retrieval, because some users already express their intent accurately.3 For web-sourced indexes this is a common case. A user who pastes an error code, a flag name or a version string has already written a precise keyword query. A rewrite that paraphrases it away can turn an exact match into a near miss; the BM25 vs embeddings post covers why exact strings need a keyword path.
Check what your framework does by default. In LangChain's MultiQueryRetriever, include_original defaults to False, and the default prompt asks for 3 different versions of the question.45 The source shows two more details.5 When include_original is on, the original query is appended after the generated ones. The results for each query are then concatenated in query order, and duplicates are removed by keeping each document's first occurrence. There is no fusion score.
Take three queries with illustrative results: the first rewrite returns B, D, A; the second D, B, E; the original A, B, C. The merged list is B, D, A, E, C. If you cut that list to a top-3, the user's own best match, A, comes third, and C, which only the original query found, is last. Nothing about the user's words gave them priority.
Fuse the lists and weight the original
A small change fixes this: fuse the per-query lists with reciprocal rank fusion and give the original query's list a larger weight. The RRF post explains the constant.
def weighted_rrf(rankings, weights, k=60):
"""Fuse ranked lists of IDs; rank starts at 1."""
scores = {}
for ranking, weight in zip(rankings, weights):
for rank, doc_id in enumerate(ranking, start=1):
scores[doc_id] = scores.get(doc_id, 0.0) + weight / (k + rank)
return sorted(scores, key=lambda d: -scores[d])
original = ["A", "B", "C"]
rewrite_1 = ["B", "D", "A"]
rewrite_2 = ["D", "B", "E"]
lists = [original, rewrite_1, rewrite_2]
print(weighted_rrf(lists, [1, 1, 1])) # ['B', 'D', 'A', 'C', 'E']
print(weighted_rrf(lists, [2, 1, 1])) # ['B', 'A', 'D', 'C', 'E']
With equal weights, D scores 1/62 + 1/61 ≈ 0.03252 and edges out A at 1/61 + 1/63 ≈ 0.03227. With the original weighted 2, A rises to 2/61 + 1/63 ≈ 0.04866 and moves to second, and C, found only by the original, rises to 2/63 ≈ 0.03175. The weight is a knob, not a recommendation: try 1 and 2 on your question set and keep what your misses favor.
Cost, and how to decide
Every rewrite is one more model call and one more search per question. DMQR-RAG treats this as a problem to solve: its adaptive step picks a subset of strategies for each query, which brought the average from four rewrites to about 2.5, nearly 40% fewer.3 HyDE adds a generation step that has to finish before retrieval can start.
A test that fits in an afternoon:
- Read your misses first. Run your golden questions with the original query only. Mark the misses where the right chunk exists but the question's wording does not match it. If there are few, rewriting has little to fix.
- Add one technique at a time. Try HyDE or multi-query, not both, and keep the original query in the search.
- Compare at the k you pass to the model. Recall at 50 can rise while the top 5 gets worse.
- Look at the questions with exact strings. If they lose ground, raise the original query's weight or route those questions around the rewrite.
Footnotes
-
Gao, Ma, Lin and Callan, "Precise Zero-Shot Dense Retrieval without Relevance Labels", arXiv 2212.10496 (December 2022). ↩ ↩2
-
Eibich, Nagpal and Fred-Ojala, "ARAGOG: Advanced RAG Output Grading", arXiv 2404.01037 (April 2024). ↩ ↩2 ↩3 ↩4
-
Li et al., "DMQR-RAG: Diverse Multi-Query Rewriting for RAG", arXiv 2411.13154 (November 2024). ↩ ↩2 ↩3 ↩4 ↩5 ↩6
-
LangChain Python reference,
MultiQueryRetriever.from_llm. ↩ -
LangChain source,
langchain_classic/retrievers/multi_query.py. ↩ ↩2
Frequently asked questions
Does HyDE improve RAG retrieval?
In the ARAGOG study, HyDE significantly improved retrieval precision over a naive RAG baseline. That study used 107 questions over a corpus of 423 AI papers with GPT-3.5-turbo, so test it on your own question set before you turn it on.
Does multi-query retrieval help RAG?
The evidence is mixed. ARAGOG reported a reduction in retrieval precision for multi-query compared with naive RAG, while DMQR-RAG reported gains over RAG-Fusion with its own set of four rewriting strategies. Which result your data follows is something only your own evaluation can show.
Should I keep the original query when rewriting?
Yes, as one of the queries. DMQR-RAG keeps the original query in its retrieval set because some users already state their intent accurately. In LangChain's MultiQueryRetriever this is the include_original setting, which defaults to False.
How many query rewrites should I generate?
LangChain's default prompt asks for 3 versions. DMQR-RAG's adaptive selection cut its average from four rewrites to about 2.5 per query. Each rewrite adds an LLM call and a search, so start small and measure.
Sources
- ARAGOG: Advanced RAG Output Grading (arXiv 2404.01037) (Paper)
- DMQR-RAG: Diverse Multi-Query Rewriting for RAG (arXiv 2411.13154) (Paper)
- Precise Zero-Shot Dense Retrieval without Relevance Labels (HyDE, arXiv 2212.10496) (Paper)
- MultiQueryRetriever.from_llm (LangChain Python reference) (Documentation)
- langchain_classic/retrievers/multi_query.py (LangChain source) (Documentation)