Coderhouse goes global

🌍

Read more

What Is Query Rewriting? How AI Engineers Improve RAG Retrieval With Query Expansion and HyDE

AI Engineering

Build and ship real applications with LLMs, agents and automation.

8 weeks · Live online · View course →

Data Analytics

Go from zero to job-ready analyst with SQL, Python and BI tools.

10 weeks · Live online · View course →

Dan Patiño

AI Strategy & Innovation at Coderhouse

Artificial Intelligence

What Is Query Rewriting? How AI Engineers Improve RAG Retrieval With Query Expansion and HyDE

What Is Query Rewriting? How AI Engineers Improve RAG Retrieval With Query Expansion and HyDE

Query rewriting is the step in a retrieval-augmented generation (RAG) pipeline where the user's original question is transformed into one or more better search queries before anything is retrieved. Instead of sending "why did my refund take so long?" straight to a vector index, the system might rewrite it into "refund processing time policy" and "refund delays causes", search with both, and merge the results.

It matters because retrieval is usually the weakest link in a RAG app. Users write short, vague, conversational or misspelled questions, and they often depend on earlier turns in a chat ("and what about the enterprise plan?"). If the retriever gets a poor query, it returns poor chunks, and even the best model will answer from the wrong context. For AI engineers, query rewriting is one of the cheapest ways to lift retrieval quality without re-indexing the whole knowledge base.

Where query rewriting fits in a RAG pipeline

A typical RAG pipeline has four stages: understand the question, retrieve candidate chunks, optionally rerank them, and generate the answer. Query rewriting sits at the very beginning, between the user and the retriever:

  1. Input: the raw user message, plus chat history if there is any.

  2. Rewrite: an LLM (or a rule-based step) produces one or several search-ready queries.

  3. Retrieve: each query runs against the vector store, a keyword index or both.

  4. Fuse and rerank: results are merged, deduplicated and ordered before they reach the generator.

The answer is still generated from the user's original question. The rewritten queries exist only to find better evidence.

The main query rewriting techniques

1. Conversational rewriting (standalone questions)

In chat interfaces, follow-up questions are incomplete on their own. "Does it support SSO?" means nothing to a retriever unless you know the previous turn was about a specific product. The fix is to ask an LLM to turn the latest message plus recent history into a standalone question: "Does the Acme Analytics enterprise plan support single sign-on?" This is the most common rewriting step in production chatbots, and often the one with the biggest impact.

2. Query expansion and multi-query retrieval

Query expansion is an old information retrieval idea: add synonyms, related terms or alternative phrasings so the search matches documents that use different vocabulary. With LLMs, the modern version is multi-query retrieval: generate three to five different versions of the question, run each one, and combine the results. LangChain ships it as the MultiQueryRetriever. It helps when one concept has many names, such as "churn" and "cancellations".

3. Decomposition into sub-questions

Some questions bundle several information needs: "Compare the refund policy and the SLA for the basic and pro plans." A single embedding of that sentence is a blurry average of four topics. Decomposition splits it into focused sub-queries (basic refund policy, pro refund policy, basic SLA, pro SLA), retrieves for each, and lets the generator assemble the comparison.

4. HyDE: hypothetical document embeddings

HyDE, introduced in the paper Precise Zero-Shot Dense Retrieval without Relevance Labels, flips the problem around. Instead of embedding the short question, you ask an LLM to write a plausible answer passage, embed that hypothetical passage, and search for real documents that look like it. The generated text may contain wrong details, but its vocabulary and structure resemble the documents you want, so the embedding lands closer to them. HyDE tends to help with short or abstract questions and adds one LLM call of latency.

5. Step-back and keyword rewriting

Step-back prompting asks the model for a more general version of the question ("What factors affect refund processing time?") and retrieves for both the general and the specific query. Keyword rewriting goes the other way: it converts a natural-language question into precise terms, product names or error codes, which works well with the sparse side of hybrid search.

6. Trained rewriters

Research such as Query Rewriting for Retrieval-Augmented Large Language Models proposes a "rewrite-retrieve-read" setup in which a smaller model is trained specifically to produce queries that lead to better final answers. Most teams start with prompted rewriting first.

Comparing the techniques

Technique

Best for

Main cost

Standalone question

Multi-turn chat and follow-ups

One small LLM call

Multi-query / expansion

Vocabulary mismatch, synonyms

More retrieval calls, need for fusion

Decomposition

Comparisons and multi-part questions

More calls, more complex orchestration

HyDE

Short or abstract questions

Extra generation latency

Keyword rewriting

Codes, product names, exact terms

Can drop useful context

How AI engineers implement query rewriting in production

  • Use structured outputs. Ask the rewriter to return JSON, for example a list of queries and a flag for whether retrieval is needed at all. Greetings and small talk do not need a search.

  • Keep the rewriter small and fast. A lightweight model is usually enough, and it keeps latency and cost under control.

  • Fuse results carefully. When several queries return overlapping chunks, deduplicate them and combine rankings, for instance with reciprocal rank fusion, before passing the top results to a reranker.

  • Preserve constraints. Rewrites must not lose filters such as product, region, date range or customer tier. Pass those as metadata filters instead of trusting the model to keep them in text.

  • Log original and rewritten queries. Traces that show both make it easy to see when a rewrite drifted away from what the user meant.

  • Add a fallback. If the rewriter fails or times out, search with the original query rather than failing the whole request.

How to measure whether rewriting helps

Query rewriting is not automatically better. A rewrite can invent intent, over-generalize, or add latency for no gain. Treat it like any other change and test it on a fixed evaluation set:

  • Compare retrieval metrics such as recall@k, hit rate and MRR with and without rewriting, as described in this guide to RAG evaluation.

  • Check end-to-end answer quality, groundedness and the rate of "I don't know" responses.

  • Track p95 latency and cost per request, since multi-query and HyDE multiply calls.

  • Slice results by query type: follow-ups, short keyword queries and long multi-part questions often behave differently.

Common mistakes

  • Rewriting every message. Clear, specific questions often retrieve better as they are.

  • Answering the rewritten question. The generator should respond to what the user asked, not to the internal search query.

  • Too many variants. Ten queries rarely beat three or four, and they flood the context with near-duplicates.

FAQ

Is query rewriting the same as prompt engineering?

No. Prompt engineering shapes how the model answers. Query rewriting shapes what the retriever searches for, so it improves the evidence the model receives.

Do I need query rewriting if I already use hybrid search and reranking?

They solve different problems. Hybrid search and reranking improve how documents are matched and ordered; rewriting improves the query itself. Many production systems use all three.

Which technique should I try first?

For chat apps, start with standalone-question rewriting. For search over large, varied documentation, try multi-query retrieval with result fusion, then measure.

Keep learning with Coderhouse

Designing retrieval that holds up with real users is core AI engineering work. Choose your next step:

  • Forward Deployed AI Engineering Course — for engineers with production experience who want to build RAG pipelines, agents and evals and deploy them inside real organizations.

  • Data Analytics Course — learn SQL, Python and statistics to measure what works, from retrieval metrics to business KPIs; no coding background needed.

  • GTM Engineer Course (waitlist) — join the waitlist to be the first to know when enrollment opens for the program on go-to-market engineering.

Dan Patiño

I'm Dan Patiño, head of AI Strategy & Innovation at Coderhouse. My day-to-day work involves merging the tactical management of e-commerce (CRO, Email Marketing and SEO) with the development of disruptive solutions. I specialize in building internal AI-powered apps to automate tasks and boost innovation within the team. I firmly believe that technology is strategy's best ally. To dive deeper into my professional journey, I'll be waiting for you on my LinkedIn profile.