# What Are Query Rewriting and Expansion?

> What query rewriting and expansion are, how they close the gap between a user's words and your documents, and what they cost, for your AI interview.

**In short:** Query rewriting and query expansion change the user's question before the search runs. Rewriting writes a clearer version of the question, sometimes a few alternatives, while expansion adds related terms or extra query variants, so the search finds documents written in different words.

AI and LLM interview question Q127, Retrieval-augmented generation (RAG). Intermediate, common (our estimate). From Venkat R. Murty's free Interview Kit: https://designervenkat.online/interview/ai/what-are-query-rewriting-and-expansion

## Say it in 30 seconds

Query rewriting and expansion change the question before it reaches the search. People ask in their own words, but documents use the company's words, so a plain search can miss. Rewriting writes a clearer version of the question, or a few alternatives, using the earlier chat when needed. Expansion runs several versions or adds related terms, then merges the results. Both cost an extra model call and can drop exact codes or drift off topic. So I keep the original query in the search too, skip rewriting for exact lookups, and measure the results.

## Say it in 2 minutes

A search matches the words in the question against the words in the documents. Staff use their own words, and policies use the company's words. An HR assistant at a mid-size bank gets this message: "can I claim my phone bill from my Pune trip?" The policy talks about telecom expenses on official travel. A plain search finds nothing useful. Query rewriting and expansion close that gap before the search runs.

Rewriting writes a clearer version of the question, or a few alternatives, and the search can use them alongside the original. A model reads the message and the chat so far, fixes typos, and uses the policy's words. A follow-up such as what about last month only makes sense with the earlier turns, so the rewriter needs them. The search can still use the original question, which keeps the exact words.

Expansion makes several queries, or adds related terms, and merges the results. A 2023 study on prompting language models for expansion found that step-by-step prompts gave useful extra terms. Expansion finds more documents, but it can also pull in noise, such as travel booking rules that do not answer a phone bill question.

Both have costs. Each rewrite is an extra model call, so every search waits longer and costs more. A rewrite can drop an exact code such as a policy ID. So I keep the original query in the search, skip rewriting for exact lookups, and test on real staff questions before and after the change.

## What are query rewriting and expansion, in plain words?

A search engine matches the words in a query against the words in your documents. People ask in their own words. Documents use the company's words. Query rewriting and query expansion close that gap before the search runs.

Think of a bank teller. A customer asks about sending money abroad, and the teller knows the form sits under international transfers. The teller turns the request into the bank's own words. Query rewriting does the same job for a search engine.

Here is the AI version. The HR assistant in the worked example gets a question about phone bills after a trip, and the policy says telecom, not phone.

- **Query rewriting:** Turning the question into a clearer search query, or a few, often with a model.
- **Query expansion:** Adding related terms, or running several query variants and merging the results.
- **Recall:** The share of the right documents that the search actually finds.
- **Query drift:** The search wandering off the topic the user asked about, after a bad rewrite.
- **Exact match:** Finding the same word or code, such as a policy ID, word for word.

## How does query rewriting work?

A model reads the message, plus the chat so far, and writes search queries. Microsoft's Foundry IQ service (Azure AI Search) runs this step and describes it in its own docs. It also says the step is in preview.

> "The Foundry IQ service sends the search query (or a variation of it) to a generative model that generates alternative queries." (Microsoft, Foundry IQ (Azure AI Search) docs)
>
> "The rewritten queries might not contain all of the exact terms the original query had. This might impact search results if the query was highly specific and required exact matches for unique identifiers or product codes." (Microsoft, Foundry IQ (Azure AI Search) docs)

*Diagram, One question, clearer search queries: The staff question and the earlier chat go into a rewriter model. It writes clearer queries, and the search runs on them and the original against the policy index. The best match comes back as the answer, drawn from a real policy.*
1. The staff question goes to the rewriter.
2. The earlier chat goes too, so follow-ups make sense.
3. The model writes clearer queries in the policy's words.
4. The search runs on those queries and the original, against the policy index.
5. The best-matching policy comes back as the answer.

1. **Read the chat too:** A follow-up such as what about last month only makes sense with the turns before it.
2. **Write clearer queries:** Fix typos, use the policy's words, and drop the chatter.
3. **Keep the original query:** Microsoft's Foundry IQ service searches with the original query and the rewritten ones together. Do the same, so exact words still count.

## How does query expansion differ?

Expansion starts from the same question but makes a wider search. It adds related terms, or it writes several query variants, searches with each one, and merges the lists. Its aim is recall, the share of right documents a search finds.

> "Query expansion is a widely used technique to improve the recall of search systems." (Jagerman and colleagues, 2023 paper)
>
> "The document captures relevance patterns but is unreal and may contain false details." (Gao and colleagues, 2022 paper (HyDE, a made-up answer method))

*Diagram, Expansion: many queries, one merged list: One question becomes several queries, and their results are merged into one list with duplicates removed. Then the ranking step puts the best matches first. More variants find more right documents, but each one can also bring in noise.*
1. The question is turned into several search queries.
2. All the versions search, and their hits are merged into one list.
3. The best matches go on to the ranking step.

- **Rewriting: One or a few clearer queries.** Writes a clearer version of the question, and searches with it plus the original. One rewrite can drop an exact term, such as a policy code.
- **Expansion: Many queries, merged.** Finds more right documents, but costs more search time and can bring in noise.
- **HyDE: A made-up answer.** The model writes a fake answer based on the question, then searches for real text that looks like it.

Papers from 2023 tried both ways. Ma and colleagues had a model write the query for a web search. Wang and colleagues had a model write pseudo-documents, which are made-up passages, and added them to the query.

## What goes wrong, and what does it cost?

Here is a small, made-up version of the HR assistant. The index holds a few policy lines. A plain search of the staff question finds nothing, and a model-written rewrite finds the right lines. The model call is stubbed out, so you can run the code as it is.

```python
# A made-up HR policy index. Search matches shared words only, so word gaps show up.
POLICY = {
    "P1": "Mobile and telecom expenses on official travel are reimbursed up to a monthly cap.",
    "P2": "Travel must be booked through the approved portal.",
    "P3": "Claims are filed within 30 days of return.",
}

def search(query):
    words = set(query.lower().replace("?", "").split())
    return [pid for pid, text in POLICY.items()
            if words & set(text.lower().replace(".", "").split())]

# A model would write these rewrites. Here they are typed in by hand.
question = "can I claim my phone bill from my Pune trip?"
rewrite = "reimbursement for mobile telecom expenses on official travel"
expansion = ["claims for travel phone expenses", "mobile phone bill claim policy"]

print("question:", search(question))
print("rewrite:", search(rewrite))
for q in expansion:
    print("variant:", search(q))
```

Output:

```text
question: []
rewrite: ['P1', 'P2']
variant: ['P1', 'P2', 'P3']
variant: ['P1']
```

The rewrite finds the telecom policy, and also the travel booking rule, because that line shares the word travel. The expansion finds more, and some of it is noise.

- **Delay and money:** Every search waits for an extra model call.
- **Lost exact terms:** A rewrite can drop a policy code, a product ID or a name that must match word for word.
- **Noise:** Expansion brings in documents that share one word but answer a different question.
- **Drift:** A bad rewrite changes what the user asked, and nobody notices unless someone checks.

> **Tip:** Asked how to improve retrieval? Don't say rewriting always helps. Say you keep the original query, skip rewrites for exact lookups, and test before and after on real questions.

### How would you set up rewriting for that HR assistant?

1. **Log every rewrite:** Store the question, the rewrite and the hits, so you can see what changed and why.
2. **Keep the original query:** Search with both the question and the rewrite, so exact words still count.
3. **Skip codes and IDs:** If the question holds a policy code such as HR-7.2, search it as typed.
4. **Test before and after:** Label a set of real staff questions with the right policy, then compare hits with and without rewriting.

Time the extra model call in the logs, so the delay has a number on it before anyone argues about it.

## What does the interviewer want to hear?

**A strong answer covers**

- [ ] A plain definition: rewrite the question, or search several versions of it, so the search finds more.
- [ ] The gap it closes: users and documents use different words.
- [ ] Rewriting versus expansion, with one example of each.
- [ ] The costs: an extra model call, lost exact terms and noise.
- [ ] Measurement on a labelled set of real questions, before and after.
- [ ] Keep the original query, and skip rewriting for exact codes.

**Common traps**

- Trap: "Rewriting always makes search better." Better: It can help or hurt. Measure on real questions, and keep the original query too.
- Trap: "Just use a bigger model to rewrite." Better: A bigger model adds cost and delay, and it can still drop an exact code. Fix the rules first.
- Trap: "Expansion is free, it is only more queries." Better: Each extra query costs search time, and the merged list can hold more noise. Check the top results.

## Can you spot the risky rewrite?

**Spot the risky rewrite:** A staff member asks about the phone cap on business trips and types the policy code HR-7.2. Which rewrite is the risky one?

A. Phone cap for business trips under the current policy
B. HR-7.2 phone cap for business trips
C. Current mobile reimbursement cap, policy HR-7.2 and trips
D. Business trip phone limits, HR-7.2 cap

**Answer:** A. It drops HR-7.2, the exact ID the staff member typed. A search for that code, word for word, finds the one policy. A loose rewrite can miss it or pull in others. Keep codes in the query, or skip rewriting for them.

**Quick check:** Exact lookups started failing after you added a rewriting step. What is the first fix?

A. Use a bigger rewriting model
B. Skip rewriting for exact lookups and keep the original query
C. Delete the policy index and rebuild it
D. Lower the temperature of the rewriter

**Answer:** B. Exact lookups need the words as typed. Keep the original query and skip rewrites for those lookups. A bigger model adds cost and can still drop the code.

## Can you answer these from memory?

**Flash cards**

- **What is query rewriting?** Turning the user's question into a clearer search query or a few, often with a model.
- **What is query expansion?** Adding related terms or several query variants, then merging the results.
- **Main risk of rewriting?** It can drop exact terms, such as codes, product IDs and names.
- **Why keep the original query?** A bad rewrite then still leaves the user's exact words in the search.
- **What does HyDE do?** Writes a made-up answer, then searches for real text that looks like it.
- **How do you know it helps?** Compare hits before and after, on a labelled set of real questions.

## Likely follow-up questions

- Q123 What is hybrid search (BM25 + vectors)? https://designervenkat.online/interview/ai/what-is-hybrid-search
- Q124 What is BM25? https://designervenkat.online/interview/ai/what-is-bm25
- Q126 Rerankers: cross-encoder vs bi-encoder? https://designervenkat.online/interview/ai/cross-encoder-vs-bi-encoder-rerankers
- Q128 What is HyDE? (full answer coming)
- Q131 Retrieval metrics: recall@k, MRR, nDCG? https://designervenkat.online/interview/ai/retrieval-metrics-recall-at-k-mrr-ndcg
