Query Rewriting, Multi-Hop, SQL and Multimodal RAG
Techniques for questions that one search cannot answer, with their costs, their failure modes and tested examples.
When a single search fails, improve the question (rewrite, expand or decompose it), search in steps where each result shapes the next query, ask databases through controlled queries instead of searching them as text, and index non-text content in a form that can be found and cited. Each technique adds calls, latency and new ways to fail, so use it only for the question types that need it.
What you will learn: query rewriting, expansion and decomposition, multi-hop and iterative retrieval, structured retrieval with SQL, multimodal retrieval and how to route between them.
Prerequisites: RAG Explained and Agentic RAG and Embeddings, Vector and Hybrid Search, Reranking.
Four questions basic retrieval struggles with
| Question | Why one search fails | Technique |
|---|---|---|
| "What about the other one?" | Meaning depends on the conversation | Rewriting |
| "Compare our leave rules in India and Spain" | Two needs in one sentence | Decomposition |
| "When is the holiday at the project lead's office?" | The second query depends on the first answer | Multi-hop |
| "Total open invoices by region" | Needs computation over records | Structured query |
Rewriting, expansion and decomposition
Rewriting
Turn a conversational fragment into a standalone query. "And for contractors?" becomes "What is the laptop replacement policy for contractors?" Give the rewriter the recent turns, ask for the query only and keep the original alongside, since a rewrite can drop a crucial word. Search both when unsure.
Expansion
Add synonyms, official terms and abbreviations from a glossary, or generate a few paraphrases and fuse their results. A related method, HyDE, asks a model to write a hypothetical answer and uses its embedding to search, on the idea that an answer resembles relevant documents more than the question does. The invented text must never be shown or cited as fact, and it can steer search wrong when the model knows little about your domain.
Decomposition
Split a compound question into independent parts, retrieve for each, then combine. Independent parts can run in parallel. Keep track of which evidence answers which part, so that you can say when one part has none.
| Technique | Extra cost | Main risk |
|---|---|---|
| Rewrite | One small model call | Intent changes |
| Multi-query expansion | Several searches | Noise and drift |
| Hypothetical answer | One generation call | Wrong assumptions steer search |
| Decomposition | Calls per part | Parts that miss the real question |
Multi-hop and iterative retrieval
Some answers form a chain. The agent must find one fact before it knows what to ask next. Research on interleaving reasoning with retrieval, such as IRCoT, and the ReAct pattern do this: reason, search, read, decide the next query.
"""Multi-hop retrieval: the answer to one search forms the next query."""
import re
DOCS = {
"projects": "Project Atlas is led by Priya Nair.",
"people": "Priya Nair works in the Hyderabad office.",
"offices": "The Hyderabad office closes for holiday on 2 October.",
"other": "Project Borealis is led by Sam Ortiz.",
}
def search(*terms):
"""Return the document that contains every term."""
for name, text in DOCS.items():
if all(t.lower() in text.lower() for t in terms):
return name, text
return None, None
PLAN = [ # the questions a model would produce; {x} is filled from earlier hops
(("Project {x}", "led by"), r"led by ([A-Z]\w+ [A-Z]\w+)"),
(("{x}", "office"), r"in the (\w+) office"),
(("{x} office", "holiday"), r"on (\d+ \w+)"),
]
def multi_hop(start, max_hops=4):
value, trail = start, []
for terms, pattern in PLAN[:max_hops]:
query = [t.format(x=value) for t in terms]
name, text = search(*query)
match = re.search(pattern, text or "")
if not match:
return None, trail + [(query, "no evidence")]
value = match[1]
trail.append((query, name))
return value, trail
for start in ("Atlas", "Borealis"):
answer, trail = multi_hop(start)
print(f"When is the holiday for the lead of {start}?")
for query, source in trail:
print(f" search {query} -> {source}")
print(" answer:", answer or "cannot be established from the sources")
Output:
When is the holiday for the lead of Atlas?
search ['Project Atlas', 'led by'] -> projects
search ['Priya Nair', 'office'] -> people
search ['Hyderabad office', 'holiday'] -> offices
answer: 2 October
When is the holiday for the lead of Borealis?
search ['Project Borealis', 'led by'] -> other
search ['Sam Ortiz', 'office'] -> no evidence
answer: cannot be established from the sources
The plan here is fixed so that the mechanics are visible; a model would generate each next query from what it just read. The second run is the important one. A missing link ends the chain with an honest statement instead of a guessed office. Errors compound across hops: if each hop is right nine times in ten, three hops are right only about seven times in ten, assuming independent errors.
Controls for iterative search
- A maximum number of hops, searches and tokens.
- Detection of repeated or near-identical queries.
- A record of which source supports each intermediate fact.
- A sufficiency check: can each part of the question now be answered from evidence?
- A defined way to stop and report what is missing.
Designs such as Self-RAG and Corrective RAG add steps that judge whether retrieved material is relevant and whether to search again or elsewhere. Agent Decisions: Confidence, Stopping, Loops and Budgets covers stopping rules.
SQL and structured data retrieval
Totals, filters, rankings and joins belong to a database. Embedding rows and hoping a model adds them up gives wrong answers with great confidence. There are three levels of freedom.
| Approach | The model chooses | Safety | Coverage |
|---|---|---|---|
| Approved queries | Which query and its values | Highest | Known questions |
| Semantic layer | Metrics, dimensions and filters | High | Modeled data |
| Generated SQL | The whole statement | Needs strong guardrails | Broad |
"""Structured retrieval: the model picks a query and values, never writes SQL."""
import sqlite3
db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE invoice (id INTEGER, tenant TEXT, region TEXT, amount REAL, status TEXT);
INSERT INTO invoice VALUES
(1,'acme','north',120,'open'), (2,'acme','north',300,'paid'),
(3,'acme','south',80,'open'), (4,'globex','north',999,'open');
""")
QUERIES = {
"open_total_by_region": (
"SELECT region, SUM(amount) FROM invoice "
"WHERE tenant = :tenant AND status = 'open' GROUP BY region ORDER BY region",
set()),
"invoices_over": (
"SELECT id, amount FROM invoice "
"WHERE tenant = :tenant AND amount > :minimum ORDER BY id LIMIT 50",
{"minimum"}),
}
def run(tenant, name, args):
"""tenant comes from the session, not from the model."""
if name not in QUERIES:
return "refused: unknown query"
sql, wanted = QUERIES[name]
if set(args) != wanted:
return f"refused: arguments must be {sorted(wanted)}"
if not all(isinstance(v, (int, float)) for v in args.values()):
return "refused: numbers only"
return db.execute(sql, {**args, "tenant": tenant}).fetchall()
print(run("acme", "open_total_by_region", {}))
print(run("acme", "invoices_over", {"minimum": 100}))
print(run("acme", "invoices_over", {"minimum": "0 OR 1=1"}))
print(run("acme", "invoices_over", {"minimum": 0, "tenant": "globex"}))
print(run("acme", "drop_table", {}))
Output:
[('north', 120.0), ('south', 80.0)]
[(1, 120.0), (2, 300.0)]
refused: numbers only
refused: arguments must be ['minimum']
refused: unknown query
The tenant comes from the session, every value is passed as a parameter and unexpected queries or arguments are refused. The model gets flexibility only where you allow it. When open questions require generated SQL, use a read-only role limited to approved views, row-level security, statement timeouts, row limits and a parser that permits only a single read statement; show the query to the user and test results against known answers. See Text-to-SQL Agents and Schema Linking and Safe SQL, Permissions and Evaluation.
The statement may run and return a number that answers a different question: gross instead of net, all regions instead of one. Define metrics once, state the filters used in the answer and keep a test set of questions with verified results.
Multimodal retrieval: images, audio, video and PDFs
Much knowledge is not plain text: diagrams, screenshots, scanned forms, meetings and training videos. There are two broad designs, and they can be combined.
| Content | Index | Citation unit | Typical error |
|---|---|---|---|
| PDF pages | Layout-aware text plus page images | Document and page | Lost tables |
| Images and diagrams | Captions, recognized text, visual embeddings | Image and region | Invented description |
| Audio | Transcript with speakers and times | Timestamp range | Misheard names and numbers |
| Video | Transcript, key frames, on-screen text | Time range | Visual events never mentioned aloud |
Contrastive models such as CLIP showed that text and images can share an embedding space. Page-image retrieval methods such as ColPali search documents visually without first extracting text. Whatever the method, keep a pointer to the original so that a person can verify, mark generated descriptions as generated, and apply the source's permissions to every derived item.
Numbers read from charts and photos deserve a check. Where an action depends on a figure, obtain it from the underlying data or ask a person to confirm. Multimodal, Vision, Video and Document Agents goes further.
Routing and combining
A router, either rules or a small classifier, sends each question to the cheapest method likely to work.
| Signal in the question | Route |
|---|---|
| Identifier or error code | Keyword search first |
| Totals, averages, "how many" | Structured query |
| "Compare", several named entities | Decompose |
| Chain of relationships | Multi-hop or graph retrieval |
| "Show the diagram" | Media search |
| Greeting or general knowledge | No retrieval |
Log the chosen route and let the agent fall back to another when evidence is weak. Misrouting is a failure type of its own, so label the intended route in your test set and measure it.
Deciding whether it was worth it
Build the test set by question type. For each technique compare, on the types it targets and on all others: evidence recall, answer correctness, searches and tokens per question and latency at the slow end. Keep a technique only if it improves its target types without damaging the rest. A common finding is that rewriting helps conversation follow-ups greatly and does little elsewhere, which argues for applying it selectively.
The helpdesk receives policy questions and "how much did we spend" questions. The team routes the first to hybrid search and the second to a dozen approved queries with parameters. Compound questions are split. Anything the router cannot classify goes to document search, with a note that figures require the reporting tool.
Putting it in an agent
An agent usually receives these techniques as tools rather than as a fixed pipeline. Describe each tool by what it is good for, so the model can choose.
| Tool | Description given to the model | Returns |
|---|---|---|
| search_documents | Policies, guides and notes; use short specific queries | Passages with identifiers and dates |
| open_document | Read a section found by search | Text with its heading path |
| run_report | Totals and lists from approved queries | Rows plus the filters applied |
| search_media | Diagrams, scans and recordings | Page or time references |
Return results the model can act on. "No results; the filter region=east removed all 12 matches" lets it adjust sensibly, provided the message reveals nothing the user may not know. An empty list invites random retries. Include dates and identifiers with every passage, truncate long results with a way to read more, and keep a running list of evidence so that the final answer cites what was actually read.
Budgets across techniques
Give one shared budget for the whole question, covering searches, model calls and time, so that expansion, decomposition and extra hops cannot multiply each other. Four rewrites of three sub-questions over three hops is already thirty-six searches. When the budget is nearly spent, the agent should answer what it can support and name what remains open.
Security of retrieved text
More searching means more chances to read hostile content, and a retrieved passage can contain instructions. Treat results as data, keep consequential tools out of reach during research steps and do not let retrieved text choose which database query runs. See Prompt Injection Attacks and Defenses and RAG Security, Freshness and Cost.
Explaining the route to users
Say briefly how an answer was obtained: which documents were read, which report was run and with which filters. People can then spot a wrong assumption, such as the wrong year or region, in seconds. Keep the full trace of queries and results for your own debugging, with content protected according to its classification.
Common mistakes
- Applying every technique to every question.
- Searching tables as text.
- No hop limit or duplicate-query check.
- Citing a generated hypothetical or description as a source.
- Forgetting permissions on derived text and thumbnails.
Checklist
- Question types are listed with test cases.
- Rewrites keep the original query available.
- Iterative search has budgets and a sufficiency check.
- Structured questions go through controlled queries with session identity.
- Media results link to an exact page or time.
- Routing decisions are logged and measured.
- Each added technique pays for its latency and cost.
Frequently asked questions
Is agentic retrieval always better?
It helps with questions that need several steps. For single-fact lookups it adds cost and latency, and more chances to wander.
Can the model just write any SQL if the database is read-only?
Read-only prevents changes, not exposure, heavy queries or wrong answers. Restrict views and rows, set limits and verify results.
Do I need a multimodal embedding model for PDFs?
Not if text extraction captures what your questions need. Test visual retrieval when layout, charts or scans carry the answer.
How do I debug a failed multi-hop answer?
Inspect each hop's query, results and extracted fact, and find the first wrong step.
References and further reading
- Gao et al.: Precise zero-shot dense retrieval (HyDE)
- Trivedi et al.: Interleaving retrieval with chain-of-thought (IRCoT)
- Asai et al.: Self-RAG
- Yan et al.: Corrective retrieval-augmented generation
- Radford et al.: CLIP
- Faysse et al.: ColPali, document retrieval with vision language models
Next steps
GraphRAG and Hybrid Graph Retrieval
Use relationships when answers span many documents.
RAG Evaluation, Grounding and Debugging
Measure retrieval and answers properly.
Build Research and Deep-Search Agents
Put iterative search to work on open research.