Sub topic 12
Rewriting and expanding queries
This chapter assumes you have read the chapters on top-k retrieval, hybrid search, and reranking. You should be comfortable with a function that takes a query string and returns ranked document ids, and with calling an LLM from Python.
Why the raw question is often a poor search query
Retrieval compares the user's text with chunk text. Users do not write text that matches your chunks. Three mismatches come up most often:
- Missing context. In a chat, "What about the enterprise plan?" depends on earlier turns. Embedded alone, it matches almost nothing useful.
- Vocabulary gap. The user asks about "cancelling a subscription", but the document says "terminating an account". A keyword search misses it. A vector search may rank it too low.
- Compound questions. "Compare the refund policy for annual and monthly plans" needs two separate passages. One embedding of the whole question lands between them and can retrieve neither well.
Query transformation fixes this on the query side. It leaves the index unchanged, so you can add it to an existing pipeline and measure the effect.
The main techniques
| Technique | What it does | Fixes | Cost |
|---|---|---|---|
| Condensing (standalone rewrite) | Turns a follow-up into a self-contained question using chat history | Missing context | One LLM call |
| Multi-query expansion | Generates several paraphrases and searches with each | Vocabulary gap | One LLM call, N searches |
| Decomposition | Splits a compound question into sub-questions | Multi-part questions | One LLM call, N searches |
| Step-back | Asks a more general question first | Questions too narrow for any single chunk | One LLM call, 2 searches |
| HyDE | Generates a hypothetical answer and embeds that | Short queries against long passages | One LLM call, 1 search |
HyDE stands for hypothetical document embeddings. An answer-shaped text, even a partly wrong one, usually sits closer in embedding space to the real passage than the question does. Never show the hypothetical answer to the user or put it in the final prompt. It is only a search key.
Condensing a follow-up question
The simplest and most valuable rewrite is condensing. Give the model the recent history and the new message, and ask for one self-contained question.
def condense_question(history, question, llm):
# history is a list of (role, text) pairs, oldest first
if not history:
return question
transcript = "\n".join(f"{role}: {text}" for role, text in history[-6:])
prompt = (
"Rewrite the final user message as a single standalone question "
"that can be understood without the conversation. "
"Keep product names, error codes, and numbers exactly as written. "
"If it is already standalone, return it unchanged. "
"Output only the question.\n\n"
f"Conversation:\n{transcript}\n\n"
f"Final user message: {question}\n"
"Standalone question:"
)
rewritten = llm(prompt).strip()
return rewritten or questionThree details matter here. The history is truncated to the last six turns, which bounds cost and keeps old topics from leaking in. The prompt tells the model to preserve identifiers. The function falls back to the original question if the model returns nothing.
Multi-query expansion with rank fusion
Expansion produces several phrasings, searches with each, and merges the rankings. You already have a merge method that does not need comparable scores: reciprocal rank fusion. The code below is self-contained and runs with stand-in llm and search functions.
import re
def reciprocal_rank_fusion(rankings, k=60):
scores = {}
for ranking in rankings:
for rank, doc_id in enumerate(ranking, start=1):
scores[doc_id] = scores.get(doc_id, 0.0) + 1.0 / (k + rank)
return sorted(scores, key=scores.get, reverse=True)
def parse_variants(text, limit):
variants = []
for line in text.splitlines():
line = re.sub(r"^\s*(?:[-*]|\d+[.)])\s*", "", line).strip()
if line and line not in variants:
variants.append(line)
return variants[:limit]
def expand_queries(question, llm, n=3):
prompt = (
f"Write {n} alternative search queries for the question below. "
"Use different wording and synonyms. Keep any identifiers exactly. "
"One query per line, no commentary.\n\n"
f"Question: {question}"
)
variants = parse_variants(llm(prompt), n)
# The original always comes first and is never dropped.
return [question] + [v for v in variants if v != question]
def multi_query_search(question, llm, search, n=3, k=5):
queries = expand_queries(question, llm, n)
rankings = [search(q, k) for q in queries]
return reciprocal_rank_fusion(rankings)[:k]
# Stand-ins so the example runs without any service.
def fake_llm(prompt):
return "1. how to terminate an account\n2. close my subscription\n3. cancel plan"
CORPUS = {
"how to cancel a subscription": ["doc_a", "doc_c"],
"how to terminate an account": ["doc_b", "doc_a"],
"close my subscription": ["doc_b"],
"cancel plan": ["doc_a"],
}
def fake_search(query, k):
return CORPUS.get(query, [])[:k]
print(multi_query_search("how to cancel a subscription", fake_llm, fake_search))
# ['doc_a', 'doc_b', 'doc_c']doc_a wins because it appears in three of the four lists. doc_b appears in only two, but it ranks first in both. Documents found by several phrasings rise, which is the intended effect.
Decomposition and step-back
For a compound question, ask the model for a short list of independent sub-questions, then retrieve for each one. The passages from all sub-questions go into the same prompt. Fusion is less useful here. The sub-questions want different documents, so you usually take the top two or three from each list instead of merging them.
Step-back works in the opposite direction. For "Why does error E4021 appear after upgrading to 3.2?", you also ask "What changed in the 3.2 upgrade?". The specific query finds the error documentation. The general one finds the release notes that explain it. Run both and merge.
Failure modes
Rewriting is not free, and it can make retrieval worse.
- Drift. The model adds details the user never asked about, and retrieval follows them. Mitigate by always including the original query and by telling the model to add nothing new.
- Lost identifiers. A paraphrase may change
ERR_CONN_RESETto "connection error". Exact tokens matter most for the keyword half of hybrid search. Instruct the model to preserve them, and consider sending the original query to keyword search and the rewrites only to vector search. - Latency. The rewrite call sits in front of retrieval, so every request waits for it. Use a small, fast model, and skip the rewrite when there is no history and the query is long and specific.
- Cost multiplication. Expanding to N queries means N searches. With a reranker on each list, the cost multiplies again. Rerank once, after fusion.
- Silent regressions. A rewrite that helps on average can hurt some query types. Evaluate it with the retrieval metrics from the evaluation chapter before and after you enable it.
When to skip transformation
Skip it when queries are already well formed, such as a search box where users type keywords, or an internal tool with structured questions. Skip it when latency budgets are tight and recall is already high. Skip it when the corpus uses very specific jargon that a general model would paraphrase away. In those cases, hybrid search and reranking usually give more improvement per unit of added latency.
Exercise
A user asks "Does it support SSO?" right after discussing the Atlas Pro plan. Retrieval returns unrelated passages. Which technique do you apply first, and what instruction should the rewrite prompt include so that the product name is not lost?
Show answer
Apply condensing, because the question depends on earlier turns. The prompt should ask for a standalone question and tell the model to keep product names, error codes, and numbers exactly as written, so the result is "Does the Atlas Pro plan support SSO?". Keep the original question as a fallback if the model returns an empty string.
Exercise
In the multiquerysearch example, why is the original question always placed first in the list of queries, and why is reranking best done after fusion rather than on each list?
Show answer
The original is kept so that a poor paraphrase can never remove the user's own wording from the search, which limits drift and preserves exact identifiers. Reranking after fusion scores each candidate once on the merged list. Reranking each list separately multiplies the cost by the number of queries and scores the same documents repeatedly.