top of page

Query Rewriting and Decomposition in RAG: Turning Messy Questions Into Searches That Work

2 hours ago
17 min read





People do not write questions for search engines. They write them in a hurry, with missing context, loose wording, and several requests packed into one sentence. A RAG system that sends that raw text straight to the index often gets weak results, and the model then answers from whatever came back.


Two techniques fix this at the front of the pipeline. Query rewriting turns a messy question into a clear search query. Query decomposition splits a complex question into smaller ones that can each be answered from a different place, and then combines the results.


This blog explains how both techniques work, where they help, where they cause harm, and how to test them before you adopt them. The CodersArts AI team wrote it for teams improving retrieval quality, and it describes general patterns that apply across models, stores, and industries.



Query Rewriting and Decomposition at a Glance


What Are They?


Rewriting replaces the user's wording with a cleaner search query. Decomposition breaks one complicated question into several simple ones, searches for each, and merges what it finds.


Why Do They Matter?


Retrieval can only find what the query points to. A vague, overloaded, or context-dependent question points to the wrong place, however good the index is.


What Do They Cost?


At least one extra language model call before search, which adds delay and spend to every request that uses them.


When Do They Help?


Follow-up questions in a conversation, questions with several parts, questions that need facts from more than one document, and queries that use different words from your content.


The Short Answer


Both techniques are inexpensive experiments with a real upside for messy and multi-part questions. Test them on your own queries before making them the default.



The Problem These Techniques Try to Solve


Most retrieval failures start with the question, not the index.


Questions Depend on Context


A follow-up such as "what about the second one?" means nothing on its own. The search sees only those words, while the meaning sits in earlier messages. Without help, the system searches for something close to nothing.


Users Pack Several Questions Into One


A single message may ask for a comparison, a date, and a recommendation at once. One search vector for all three lands in a vague middle, and none of the parts is answered well. The model then fills the gaps from general knowledge.


Wording Does Not Match the Documents


People use everyday terms, while documents use formal ones. A short, casual question may share almost no words with the passage that answers it. Keyword search then misses the passage, and vector search ranks it lower than it deserves.


Some Answers Live in Several Places


Questions that need a fact from one document and another fact from a second document cannot be satisfied by one search. The top results tend to favor one source and ignore the other. The answer is then partial, and it often sounds complete.


Noise and Filler Dilute the Signal


Greetings, hedges, and background stories make up much of a typical message. They add words without adding meaning, and they pull the embedding away from the real topic. Stripping them out gives the search a sharper target.



How Query Rewriting Works


Rewriting is a small step that sits between the user and the index.


Step One: Read the Question With Its Context


The system collects the current question and, where relevant, the recent conversation. A follow-up is read in light of what came before. This is the information the search itself would otherwise never see.


Step Two: Write a Standalone Query


A language model rewrites the question so it makes sense on its own. References such as "it" or "the second one" are replaced with the actual names. The result can be understood by someone who has seen nothing else.


Step Three: Clean and Focus the Wording


Filler is removed, and key terms are made explicit. If the user says "my login keeps failing", the rewrite might name the specific feature and symptom in the vocabulary your documents use. The query becomes shorter and more specific.


Step Four: Search With the Rewrite


The rewritten query goes to the index in place of the original, or alongside it. Most teams keep the original as a safety net. Results from both can be merged and ranked together.


Step Five: Answer From the Retrieved Text


The model answers from the passages that came back, just as in any RAG system. The rewrite itself is never shown as an answer. It exists only to improve what the search finds.



How Query Decomposition Works


Decomposition handles questions that one search cannot answer.


Step One: Detect That the Question Is Complex


The system decides whether a question has several parts or needs several sources. Some teams use a simple rule, and others ask a model to judge. Simple questions skip the process entirely.


Step Two: Split Into Sub-Questions


A model breaks the question into smaller ones, each focused on a single fact or comparison. "How does plan A differ from plan B on cancellation fees?" becomes one question about plan A, one about plan B, and perhaps one about how fees are defined. Each can be searched on its own.


Step Three: Retrieve for Each Part


Each sub-question gets its own search, sometimes against a different index or source. The results are collected per part, so each fact has the best chance of being found. Parts that do not depend on each other can run in parallel.


Step Four: Handle Dependencies


Some questions need an answer to one part before the next can be asked. The system answers the first sub-question, uses the result to form the second, and continues in order. This is often called multi-hop retrieval.


Step Five: Combine the Evidence


The retrieved passages from all the parts are gathered and handed to the model together. The model writes one answer that covers every part, using evidence from each. Good systems keep track of which passage supports which part.



Why These Techniques Can Improve Retrieval


The gains come from giving the search a better question.


A Clearer Target


A rewritten query has one topic and the right vocabulary. An embedding of that query sits closer to the passages that answer it. This helps both vector and keyword search.


Context Becomes Visible


Conversation history is folded into the query, so follow-ups no longer arrive stripped of meaning. The search sees what the user actually means. This matters most in chat-style assistants.


Each Part Gets Its Own Search


Decomposition prevents one dominant topic from crowding out the others. Every sub-question retrieves its own evidence. The final context covers more of what the question needs.


Multi-Source Questions Become Possible


When facts live in different documents or systems, decomposition lets each part go where it belongs. A single search could never do this. The result is an answer built from the right places.


No Retraining Is Required


Both techniques work with existing models and indexes. They sit in front of the retriever and need no labeled data. That makes them easy to try, and easy to switch off.



Where They Help Most


Some situations show consistent gains.


Conversational Assistants


Chat interfaces are full of follow-ups, pronouns, and half-finished thoughts. Rewriting turns each message into a query that stands alone. Without it, quality tends to fall as the conversation grows.


Comparison and Multi-Part Questions


Questions such as "how do these two options differ on price, support, and limits?" involve several lookups. Decomposition gives each lookup its own search. The final answer is more complete.


Multi-Hop Questions


When one answer is needed to find the next, a single search cannot work. Decomposition with ordered steps follows the chain. This suits research, legal, and technical questions.


Vague or Casual Phrasing


Users who do not know the right terms benefit when the rewrite supplies them. The query moves closer to the way documents are written. Retrieval improves without any change to the index.


Knowledge Spread Across Systems


Some answers sit in a document store, a database, and a ticket system. Decomposition routes each sub-question to the right source. The model then combines what comes back.



Where They Can Hurt


Neither technique is free of risk.


Questions That Were Already Clear


A precise question gains little from a rewrite, and a bad rewrite can make it worse. The model may change terms that mattered. Measure before applying these steps to every query.


Meaning Drift


A rewrite can shift the intent by adding assumptions or dropping a qualifier. The search then answers a slightly different question. Reviewing samples of rewrites catches this early.


Over-Splitting


A question that should stay together can be cut into pieces that lose their connection. The parts return passages that do not fit back together. Keep decomposition for questions that really have independent parts.


Exact-Match Needs


Names, codes, and identifiers should reach the search unchanged. A rewrite that paraphrases them can lose the match. Route these queries around rewriting, or keep the original alongside.


Added Delay and Cost


Every extra model call adds time, and decomposition adds several searches. On high-traffic systems this becomes noticeable. Apply the techniques where they earn their cost.



Writing Good Rewrite and Decomposition Prompts


The prompt decides the quality of the result.


Ask for a Query, Not a Reply


Tell the model to produce a search query, not an answer or an explanation. Without this, it may chat. Ask for plain output that the system can use directly.


Show the Conversation When It Matters


Include the recent turns for rewriting, but not the entire history. Too much text distracts the model. A few turns usually carry what is needed.


Preserve Names and Numbers


Instruct the model to keep proper names, codes, and figures exactly as written. These are the details that matter most to the search. This one line prevents many drift problems.


Limit the Number of Sub-Questions


Give a ceiling, such as a small number of parts, and ask for independent questions. Without a cap, models tend to over-split. Fewer, clearer parts retrieve better.


Use Examples From Your Own Domain


A few sample questions with good rewrites show the style you want. They help the model use your vocabulary. Update them as you learn from failures.



Variations on the Basic Ideas


Teams adapt the techniques in several ways.


Multiple Rewrites per Question


Generate a few different phrasings, search with each, and merge the results. This improves recall at a higher cost. It helps when you cannot tell which wording will match best.


Step-Back Questions


Ask a broader version of the question first, such as the general principle behind a specific case. Retrieve for both the specific and the general. This brings in background that the narrow query would miss.


Routing Sub-Questions


Send each sub-question to the source most likely to hold the answer: a document index, a database, or a web search. A small router or the model itself can decide. This keeps each search focused.


Pairing With Hypothetical Documents


Rewriting can be combined with drafting a short hypothetical answer to search with. The rewrite clarifies the question, and the draft adds vocabulary. Test the combination before trusting it.


Applying Only Where It Helps


A small classifier or rule set can send simple questions straight to search. Only messy or complex ones go through rewriting and decomposition. This keeps average cost low.



An Insurance Claims Assistant


Consider a company with an assistant that answers questions about claims and coverage.


The Problem


Customers write messages such as "I sent the photos yesterday, so what happens next and will the earlier damage on the roof be covered too?" The message depends on earlier context and holds two separate questions. A single raw search for it returns generic claims pages.


The Baseline


Searching with the message as written returns passages about photo uploads and nothing on roof coverage. The assistant answers the first part and guesses at the second. The team treats this behavior as the baseline to beat.


The Rewrite and Split


A model first rewrites the message into a standalone query that names the claim stage and the coverage question. It then splits the request into two sub-questions: what happens after documents are submitted, and whether prior roof damage is covered. Each gets its own search.


The Result


The assistant now retrieves a passage on claim review steps and a separate passage on pre-existing damage rules. The final answer covers both parts with support from the right documents. The team confirms the improvement on a set of real customer questions.


The Caveat


Messages with claim numbers or policy codes work better with direct search, so the system keeps those unchanged. The team also reviews samples of rewrites, since a small change in wording can shift the meaning. Question mixes change over time, so the measurements continue.



Bringing Query Rewriting and Decomposition Into Your RAG Pipeline


A gradual rollout keeps risk low.


Measure Your Baseline


Collect real questions and record how retrieval performs today. Mark which passages should have been found. This gives you a fixed point for every later comparison.


Add Rewriting Behind a Switch


Start with rewriting, since it is the simpler of the two. Put it behind a switch so you can compare both paths on the same questions. A language model with a short prompt is usually enough for the first version.


Introduce Decomposition for Complex Questions


Add splitting only for questions that need it, using a simple detection rule or a small classifier. Keep the number of sub-questions low. Compare results against the rewrite-only version.


Keep the Original Query Too


Search with the original as well as the rewrite, and merge the results. This protects against bad rewrites and preserves exact terms. Drop it only if testing shows it adds nothing.


Route by Question Type


Send simple lookups straight to search, and reserve the heavier steps for messy or multi-part questions. A small set of rules goes a long way. Revisit the rules as you learn from failures.



Testing and Monitoring Query Rewriting and Decomposition


These steps need their own tests, separate from the rest of the pipeline.


Build a Question Set


Include follow-ups, multi-part questions, vague questions, and exact-match queries, each with the passages that should be found. Add some questions with no answer in the knowledge base. Version the set so results stay comparable.


Measure Retrieval Directly


Check whether the right passages appear in the top results with and without each technique. Look at recall and at how high the right passage ranks. This shows whether the front-end steps help before the model is involved.


Inspect the Rewrites and Splits


Read a sample of generated queries and sub-questions. Look for dropped qualifiers, invented details, and pointless splits. Many problems show up quickly by eye.


Check Answer Quality


Better retrieval should lead to better answers, but confirm it. Compare final answers on the same questions, and check that every part of a multi-part question is addressed. A system can retrieve well and still answer poorly.


Track Delay and Cost


Record the added model calls and searches per request. Compare them with the gain in quality. If the cost is high and the gain is small, narrow where the techniques apply.



Controlling the Cost and Latency of Query Rewriting and Decomposition


Extra steps add time, so manage them.


Use a Small, Fast Model


Rewriting and splitting are short tasks that rarely need a large model. A smaller one usually does well and responds quickly. Test to find where quality starts to slip.


Cap the Number of Sub-Questions


Every sub-question means another search. A low ceiling keeps cost predictable. Most real questions need only a few parts.


Run Independent Searches in Parallel


Sub-questions that do not depend on each other can be searched at the same time. This keeps total delay close to a single search. Only dependent steps need to run in order.


Cache Repeated Questions


Common questions and their rewrites can be stored and reused. This saves model calls on repeated traffic. Clear the cache when content changes.


Skip the Steps When Direct Search Is Confident


If a plain search returns strong, clear results, the extra steps may add nothing. A simple confidence check can decide. This saves cost on the easy majority of questions.



Security and Privacy Considerations for Query Rewriting and Decomposition


The front of the pipeline handles raw user input, so treat it with care.


Where the Question Goes


The rewriting model sees the full question and sometimes the conversation. If it is a hosted service, that data leaves your environment. Review the provider's terms for retention and training use.


Guard Against Injection


A user message may contain instructions aimed at the rewriting model. Keep the prompt narrow, treat user text as data, and limit what the model can output. Validate generated queries before they reach the index.


Respect Permissions


Rewrites and sub-questions must still be filtered by what the user is allowed to see. Apply access controls at search time, not only in the prompt. Never let a rewrite widen access.


Keep Intermediate Queries Internal


Generated queries and sub-questions are working material, not answers. Do not show them to users as facts. Store them only as needed for debugging.


Log Carefully


Rewrites can repeat personal details from the question. Apply the same retention and access rules as for the original messages. Keep logs useful without keeping more than you need.



Special Cases Worth Planning For


A few situations need extra thought.


Regulated Content


Where answers affect health, finance, or legal rights, document how queries are transformed and tested. Keep a record of the sources behind each answer. Human review remains important.


Multiple Languages


Rewriting may translate or change language by accident. Check that queries stay in the language of your documents, or deliberately match it. Test each language you support.


Very Long Conversations


Long histories carry a lot of irrelevant text. Summarize older turns, and give the rewriter only what it needs. Otherwise the rewrite may pick up an old topic.


Ambiguous Questions


Sometimes the best response is a clarifying question, not a guess. Rewriting a truly unclear message can invent an intent. Consider asking the user when confidence is low.


Changing Content


Rewrites tuned to today's vocabulary can age as documents change. Retest after major content updates. Keep examples in your prompts current.



Common Mistakes With Query Rewriting and Decomposition


Applying Everything to Every Query


Simple questions do not need extra steps. Routing keeps cost down and avoids needless risk. Measure which questions benefit.


Skipping the Baseline


Without a starting measurement, you cannot tell whether a change helped. Record current results first. Keep the question set for later checks.


Dropping the Original Query


Replacing the user's words entirely can lose exact terms. Search with both where possible. Remove the original only when tests support it.


Splitting Too Aggressively


Too many sub-questions waste calls and return fragments that do not fit together. Cap the number and require independence. Keep related parts together.


Ignoring Meaning Drift


A rewrite that changes the intent is worse than no rewrite. Review samples regularly, and watch for added assumptions. Small prompt changes often fix it.


Forgetting Latency


Several model calls and searches add up. Budget the delay before launch. Parallel steps and small models help.



Advantages and Limitations of Query Rewriting and Decomposition


Where These Techniques Deliver the Most Value


Advantage

Details

No training data needed

Works with existing models and indexes.

Better follow-up handling

Conversation context becomes part of the search.

Complete multi-part answers

Each part gets its own retrieval.

Multi-source questions

Sub-questions can go to different systems.

Easy to add

Sits in front of an existing retriever and can be switched off.


What Are the Trade-Offs of Using Them?


Limitation

Details

Extra latency and cost

More model calls and searches per request.

Meaning drift

A rewrite can change what the user asked.

Exact-match weakness

Names and codes can be altered by paraphrasing.

Over-splitting risk

Parts can lose the connection that made them one question.

Needs testing

Gains vary by corpus, question type, and prompt.



How Much Do Query Rewriting and Decomposition Cost?


The direct cost is one or more extra model calls per query, usually short in both input and output. With a small, fast model, rewriting is a modest addition. Decomposition adds further searches, so cost grows with the number of sub-questions.


Latency matters as well, because these steps finish before the main search begins. Engineering time for evaluation, routing, and monitoring is typically the largest cost.


Start with a small experiment on a sample of queries, and measure the gain before putting the techniques in front of every request.



Query Improvement Techniques Compared


Rewriting and decomposition are two options among several.


Query Rewriting


A model turns the question into a clear, standalone search query. Cheap and effective for follow-ups and vague phrasing, though it cannot split a question that needs several sources.


Query Decomposition


A model splits a complex question into sub-questions, each searched on its own. Strong for comparisons and multi-hop questions, at a higher cost.


Hypothetical Document Embeddings


A model drafts a short answer and the search uses that draft. Useful when wording differs from documents, with a risk of confident drift.


Hybrid Search and Re-Ranking


Combine keyword and vector search, then re-rank the results. This improves ranking without changing the question. It works well alongside the techniques above.


Agentic Retrieval


An agent plans searches, calls tools, and loops until it has enough evidence. The most flexible option, and the hardest to control and test.


Which Teams Get the Most Value From These Techniques?


Rewriting and decomposition help teams that:


  • Run chat assistants with frequent follow-up questions

  • See multi-part or comparison questions from users

  • Need answers that draw on several documents or systems

  • Can afford one or two extra model calls per query

  • Have an evaluation set to prove the gain



Should You Add Query Rewriting and Decomposition to Your RAG System?


Add them as experiments, not as defaults. If users ask follow-ups or multi-part questions and your retrieval misses the right passages, these are among the cheapest ideas to try. If your questions are specific and your retrieval already works, you may see little gain.



How CodersArts Helps You Improve RAG Retrieval


CodersArts helps businesses make sure their RAG systems search for the right thing.


Query Analysis


We study real user questions and the ways your system misreads them. This shows whether the problem is context, wording, or complexity. The findings guide which technique to try first.


Technique Selection


We recommend and test options such as rewriting, decomposition, hybrid search, and re-ranking. Each is compared on your own data. You see what works before committing.


Evaluation Design


We build question sets and metrics that show real gains in retrieval and answers. The sets include follow-ups, multi-part questions, and exact-match cases. They keep working as a regression check.


Implementation


We add the chosen steps with routing, caching, and monitoring. Prompts and limits are set with your content in mind. The result is a pipeline your team can maintain.


Ongoing Support and Maintenance


We track quality, cost, and delay, and adjust as your content and users change. Regular reviews catch drift early. Your system keeps improving instead of slowly degrading.


Ready to improve how your RAG system understands questions? Contact CodersArts at contact@codersarts.com to review your system.



How Does a CodersArts RAG Improvement Engagement Work?


Most engagements follow four stages. A discovery session covers your documents, questions, and current results. An evaluation stage measures retrieval and tests candidate techniques.


A build stage implements the winners with monitoring. An operations stage keeps quality steady as content and usage change. Each stage ends with a clear deliverable.



Frequently Asked Questions


What Is Query Rewriting in RAG?


A step in which a model turns the user's question into a clearer, standalone search query. It resolves references, removes filler, and uses the vocabulary of your documents.


What Is Query Decomposition?


A technique that splits a complex question into smaller sub-questions. Each is searched separately, and the evidence is combined into one answer.


When Should I Use Decomposition Instead of Rewriting?


Use decomposition when a question has several parts or needs facts from different sources. Use rewriting when the question is a single request that is unclear or depends on context.


Can These Techniques Make Retrieval Worse?


Yes. A rewrite can change the meaning, and a split can break apart a question that belonged together. Testing on your own questions shows whether they help.


How Much Latency Do They Add?


At least one extra model call, and several searches for decomposition. Small models and parallel searches keep the delay modest.


Can I Combine Them With Other Techniques?


Yes. Many systems pair them with hybrid search, re-ranking, or hypothetical documents, and keep the original query alongside the rewrite.


What Should a Business Evaluate Before Adopting Them?


Evaluate your question types, retrieval quality today, tolerance for added delay and cost, and your ability to test. Also review where user questions are sent when a hosted model rewrites them.



What Services Does CodersArts Offer?


Beyond retrieval improvement for RAG and other AI and RAG specific delivery and partnership work, CodersArts offers a wider range of services that agencies, businesses, and individual developers regularly rely on, whether as part of a partnership or on their own.


AI and RAG Development


Custom AI and RAG development, starting from proof of concept through to full production builds, along with broader LLM and generative AI development for businesses building AI-powered products and internal tools.


Consultation


Project consultation for businesses and agencies evaluating an AI or machine learning initiative, helping assess feasibility, recommend the right technical approach, and scope a project before committing to full development.


One-on-One Mentorship


Personalized, expert-led mentorship for developers and teams looking to build hands-on AI, machine learning, or AI engineering skills, with guidance tailored to individual or team goals and current experience level.


Dedicated Team and Team Augmentation


Dedicated AI and machine learning engineering teams, or engineers who work as an extension of an existing in-house or agency team, scaling up or down based on project needs.


Ongoing Support and Maintenance


Post-launch monitoring, optimization, and maintenance for AI and machine learning systems already in production, helping ensure performance and reliability do not degrade over time.


Job Support Services


Remote job support for developers and engineers working on live AI, machine learning, or LLM projects, including pair programming, code reviews, workflow setup, debugging, and help meeting sprint deadlines under expert guidance.


Corporate and Team Training


Structured training and workshops for teams looking to build internal AI and machine learning capability, covering hands-on implementation as well as best practices for evaluation and production readiness.


White-Label and Partnership Delivery


CodersArts also partners with agencies, consultancies, and technology companies to deliver AI and machine learning development on their behalf, whether white-label, co-branded, or embedded alongside an existing team.


Whether you are a business improving its RAG system, an agency looking for a delivery partner, or a developer seeking hands-on mentorship, CodersArts offers services to support your AI journey.



Continue Exploring AI Resources


If you found this blog helpful, explore more AI, RAG, and enterprise AI resources from CodersArts AI to see how organizations are applying these systems to real world applications.










Comments


bottom of page