Search Tutorials
--Ads--Query Rewriting and Expansion
Turn vague user questions into clear, search-friendly queries.
Users do not write search queries; they write messages. "hey quick one, the thing about wfh fridays is that still a thing??" contains one useful idea wrapped in noise, an abbreviation and a vague reference. Query rewriting turns such input into a clear, search-friendly query before retrieval. It is the simplest member of the query transformation family covered in this module.
What rewriting fixes
| Problem | User input | Rewritten query |
|---|---|---|
| Chatty noise | "hi! can u tell me abt leave carry over pls" | leave carry-over policy unused days |
| Abbreviations | "wfh rules" | work from home remote work policy |
| Spelling errors | "reimbursment for intenet" | reimbursement for home internet costs |
| Vague wording | "is the travel thing changing?" | changes to the travel and expense policy |
| Missing domain terms | "money back for broken item" | refund or replacement for damaged products, returns policy |
A rewriting function
from rag_helpers import ask
REWRITE_PROMPT = """You rewrite user messages into search queries for a company knowledge base
(HR, finance, IT and travel policies).
Rules:
- Keep every specific detail: names, numbers, dates, product codes.
- Expand abbreviations (wfh = work from home, PTO = paid time off).
- Fix spelling. Remove greetings and filler.
- Add one or two likely synonyms used in policy documents.
- Do not answer the question. Output only the rewritten query on one line.
User message: {message}"""
def rewrite_query(message: str) -> str:
return ask(REWRITE_PROMPT.format(message=message), max_tokens=200).strip()
print(rewrite_query("hey quick one, the thing about wfh fridays is that still a thing??"))
work from home on Fridays remote work policy default remote day
Keep the original query too
Rewriting can occasionally go wrong: the LLM may drop a detail or add a wrong assumption. The safe pattern is to search with both the original message and the rewritten query and merge the results with Reciprocal Rank Fusion (from the hybrid search lesson). Good results from either query make it into the final list.
import numpy as np
from hybrid import rrf # from the hybrid search lesson
from rag_helpers import embed
def search_with_rewrite(message: str, vectors: np.ndarray, texts: list[str], k: int = 5):
rewritten = rewrite_query(message)
rankings = []
for q in (message, rewritten):
scores = vectors @ embed(q, query=True)[0]
rankings.append(list(np.argsort(-scores)[:30]))
return rewritten, [(texts[i], s) for i, s in rrf(rankings)[:k]]
Glossary expansion without an LLM
For organisation-specific abbreviations and product nicknames, a simple glossary is faster, cheaper and more predictable than an LLM:
import re
GLOSSARY = {
"wfh": "work from home",
"pto": "paid time off leave",
"lta": "leave travel allowance",
"x200": "X200 home router",
}
def expand_glossary(query: str) -> str:
def repl(m):
word = m.group(0)
return f"{word} ({GLOSSARY[word.lower()]})" if word.lower() in GLOSSARY else word
return re.sub(r"\b\w+\b", repl, query)
print(expand_glossary("WFH and PTO rules")) # WFH (work from home) and PTO (paid time off leave) rules
You can also pass the glossary to the rewriting prompt so the LLM uses your organisation's terminology.
When to rewrite
- Worth it: consumer chat interfaces, voice input (transcription errors), multilingual users, and domains with heavy jargon.
- Often unnecessary: internal search boxes used by experts who already type keyword-style queries.
- Cost: one short LLM call per question, adding latency. Keep the prompt short and use low effort, and measure whether retrieval actually improves.
Key takeaways
- Query rewriting removes noise, expands abbreviations, fixes spelling and adds domain terms.
- Tell the rewriter to keep all specific details and never to answer the question.
- Search with both the original and the rewritten query and fuse the results.
- Use a glossary for known abbreviations; it is cheap and predictable.