Suryanand/ Bootcamp
suryanand.com ↗Let's talk
← Retrieval (RAG)AI guideIntermediate#rag#query-rewriting#hyde#retrieval
Frame · ai-engineering / rag / 08-query-rewriting-and-hyde.mdGuide 020 / 103

Query rewriting and HyDE

Users do not type queries that look like the documents they need. They type "what about for contractors?" in the middle of a chat, misspell product names, or ask three questions in one sentence. Query transformation is the set of tricks that turns what the user said into one or more queries that retrieve well. It sits at the very front of the online pipeline and is often the cheapest fix for a retrieval problem that looks unfixable downstream.

Why it matters

Retrieval quality is bounded by the query. In a conversational assistant, the latest message often only makes sense with history: "and in Germany?" retrieves nothing useful on its own. Short keyword queries carry little signal for an embedding model. Compound questions ("compare our refund policy with our exchange policy") need chunks from two different places, and a single embedding of the whole question tends to land between them and retrieve neither well.

There is also a shape mismatch. Questions and answers are different kinds of text. An embedding of "How long do refunds take?" is not necessarily close to "Refunds are processed within 5 business days of approval," even though the second sentence is exactly the answer. HyDE attacks this mismatch directly.

How it works

The main techniques, from cheapest to most involved:

  • Standalone rewrite (conversational condensation). Give a small, fast model the chat history and the latest message and ask it to write a self-contained query. This is the one technique almost every chat RAG system needs.
  • Normalization and expansion. Fix spelling, expand acronyms from a glossary, add known synonyms. Can be rules or an LLM call.
  • Multi-query (query expansion). Ask the model for several paraphrases, retrieve for each, and fuse the lists with reciprocal rank fusion. This raises recall at the cost of more retrieval calls.
  • Decomposition. Break a compound or multi-hop question into sub-questions, retrieve for each, and give the generator all the evidence. Step-back prompting is a variant: ask a more general question first ("What is the refund policy?") to retrieve background.
  • HyDE (Hypothetical Document Embeddings). From Gao, Ma, Lin and Callan (ACL 2023). Ask an LLM to write a plausible answer passage, embed that passage instead of the question, and search with it. The generated passage may contain wrong details, but it has the vocabulary and shape of a real answer, so its embedding lands near real answers. The paper's insight is that the encoder's dense bottleneck filters out much of the incorrect detail, grounding the search in the actual corpus. They reported large gains over the unsupervised dense retriever Contriever without any relevance labels.
  • Self-query / filter extraction. Have the model pull structured filters out of the query ("policies updated after 2025 for the UK" becomes a date filter and a region filter plus a semantic query).
Rendering diagram…

Reference architecture

In practice you combine a few of these behind one "query planner" step. A small model can produce the standalone rewrite, a list of sub-queries and any filters in a single structured call, which keeps latency down.

Rendering diagram…

Rerank against the standalone query (the user's actual intent), not against each paraphrase. Paraphrases are a recall tool; the reranker is the precision tool.

Code

TypeScript with the OpenAI SDK: a standalone rewrite with HyDE and multi-query in one structured call, then embeddings for each search string. The search function stands in for your hybrid retriever.

import OpenAI from "openai";

const client = new OpenAI();
const MODEL = process.env.REWRITE_MODEL ?? "gpt-4.1-mini";

type Plan = { standalone: string; paraphrases: string[]; hypothetical_answer: string };

export async function planQuery(history: string, message: string): Promise<Plan> {
  const response = await client.responses.create({
    model: MODEL,
    input: [
      {
        role: "system",
        content:
          "Rewrite the user's latest message into a standalone search query using the chat history. " +
          "Also give 2 short paraphrases and a 2-3 sentence hypothetical answer written like an internal policy document. " +
          'Return JSON: {"standalone": string, "paraphrases": string[], "hypothetical_answer": string}.',
      },
      { role: "user", content: `History:\n${history}\n\nLatest message: ${message}` },
    ],
    text: { format: { type: "json_object" } },
  });
  return JSON.parse(response.output_text) as Plan;
}

export async function retrieveWithPlan(
  plan: Plan,
  search: (vector: number[], text: string) => Promise<string[]>,
) {
  const queries = [plan.standalone, ...plan.paraphrases];
  const embeddings = await client.embeddings.create({
    model: "text-embedding-3-small",
    input: [...queries, plan.hypothetical_answer],
  });
  const lists = await Promise.all(
    embeddings.data.map((e, i) => search(e.embedding, i < queries.length ? queries[i] : plan.standalone)),
  );
  return lists; // fuse with RRF, then rerank against plan.standalone
}

Note the HyDE vector is paired with the standalone text for the keyword side of hybrid search. Running BM25 on a hallucinated passage can match invented terms.

Trade-offs and pitfalls

  • Every rewrite adds latency. An extra LLM call before retrieval sits on the critical path. Use a small fast model, combine steps into one call, and skip rewriting when there is no history and the query is already specific.
  • Rewrites can drift. A model can "helpfully" narrow or change the question. Log original and rewritten queries side by side and review samples.
  • HyDE fails on unfamiliar domains. If the model knows nothing about your internal product, its hypothetical answer may use the wrong vocabulary and mislead retrieval. It works best when the domain is reasonably familiar to the model, and it is worth A/B testing per collection.
  • Hallucinated specifics. A hypothetical answer may contain an invented product code that then matches an unrelated chunk. Keep HyDE on the dense side only.
  • Multi-query multiplies cost. Three paraphrases means three to four times the retrieval work. Measure whether recall gains justify it.
  • Filter extraction must be validated. Check extracted filter values against allowed enums before passing them to the database, both for correctness and to avoid injection.

Checklist

  • Always produce a standalone query in conversational products.
  • Normalize spelling and expand acronyms from a maintained glossary.
  • Try multi-query plus RRF when recall is the bottleneck.
  • Decompose compound questions into sub-queries and retrieve for each.
  • A/B test HyDE per collection, and use it only for dense retrieval.
  • Rerank against the standalone query, not the paraphrases.
  • Log original and rewritten queries for review and evaluation.

Further reading

Why this exists README

I learn best by explaining things, so I record the explanations. Everything here is free, with no sign-up. If a lesson helps you ship something, I'd love to hear about it.