Sub topic 5
Multi-query expansion: searching with several phrasings
This chapter assumes you can build a basic RAG pipeline (index, retrieve, generate) and that you know how embedding and BM25 search work. You should also be comfortable calling an LLM with a text prompt and reading Python. The previous chapters showed why a user's raw question is often a weak search query. Here you will learn one fix: ask the model for several alternative queries, search with all of them, and merge the results.
The idea
A single query is a single guess about how the answer is worded in your documents. If the guess is off, the right passage never reaches the top-k results, and the generator has nothing to work with.
Multi-query expansion makes several guesses instead of one. The steps are:
- Send the user's question to an LLM and ask for a few differently worded search queries.
- Run each query, plus the original, against the same index.
- Merge the ranked lists into one list.
- Pass the top results to the generator.
The model's variants cover different vocabulary and different angles. A passage that one phrasing misses may be found by another.
When it helps
Multi-query expansion targets failures of wording and framing:
- Vocabulary mismatch. The user writes "can't log in" and the document says "account recovery". A variant such as "reset forgotten password" bridges the gap. This matters most with keyword search such as BM25, but it also helps embeddings when the terms are rare or domain-specific.
- Ambiguous questions. "How do I handle limits?" could mean rate limits, quota limits or file size limits. Variants can cover each reading, so the right one is likely among the results.
- Questions with several relevant angles. A question about "migrating to the new API" may need passages on authentication, endpoints and deprecations. Variants that stress different aspects pull in different passages.
It does not help much when the question is already specific and well worded. It also does not fix a question that needs facts from several steps. That case calls for decomposition or iterative retrieval, covered later.
Generating the variants
The prompt is the main design decision. Three rules keep the output usable:
- Ask for a fixed number of queries, so cost stays predictable.
- Ask for one query per line with no numbering, so parsing is a split on newlines.
- Ask for different queries. Without this, models often return near-duplicates that add cost and no coverage.
The original question stays in the query set. The variants are guesses, and the user's own words are sometimes the best match.
Parsing is defensive. Strip whitespace, drop empty lines and cut the list to n, because models sometimes return more lines than you asked for.
The implementation
The function below takes the LLM and the search function as parameters. That keeps it independent of any library and makes it easy to test. search(query, k) returns a ranked list of document ids. The merge step uses reciprocal rank fusion, which the next chapter explains in detail. It is included here so the example runs on its own.
from typing import Callable
def reciprocal_rank_fusion(rankings: list[list[str]], k: int = 60) -> list[str]:
scores: dict[str, float] = {}
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 multi_query_search(
question: str,
llm: Callable[[str], str],
search: Callable[[str, int], list[str]],
n: int = 3,
top_k: int = 5,
) -> list[str]:
prompt = (
f"Write {n} different search queries for the question below, "
f"one per line, with no numbering.\n\n{question}"
)
variants = [q.strip() for q in llm(prompt).splitlines() if q.strip()][:n]
queries = [question] + variants
rankings = [search(q, top_k) for q in queries]
return reciprocal_rank_fusion(rankings)[:top_k]To see it work without a real model or index, replace both with stubs:
def fake_llm(prompt: str) -> str:
return (
"How do I reset my password?\n"
"Account recovery steps\n"
"Forgot login credentials"
)
INDEX = {
"I can't log in": ["d1", "d4", "d2"],
"How do I reset my password?": ["d2", "d1", "d5"],
"Account recovery steps": ["d3", "d2"],
"Forgot login credentials": ["d2", "d6", "d1"],
}
def fake_search(query: str, k: int) -> list[str]:
return INDEX.get(query, [])[:k]
print(multi_query_search("I can't log in", fake_llm, fake_search))Running the two blocks together (with the stubs after the functions) prints:
['d2', 'd1', 'd3', 'd4', 'd6']Document d2 was only third for the original query. Three of the four lists contain it near the top, so it wins after fusion. Document d3 was found by only one variant, yet it still makes the final list. That is the point of the technique: a passage the original query would have missed is now in the candidate set.
Design choices and edge cases
How many variants
Three to five is a common range. Each variant adds one search call and a few more candidate passages. Returns diminish quickly, because later variants tend to repeat the earlier ones. Start with three and measure before raising it.
Running the searches
The searches are independent, so run them concurrently. With a thread pool or async client, the total latency is close to one search plus the LLM call. The LLM call is the part you cannot parallelize, since the variants must exist before you can search with them.
Duplicates and weak variants
Variants that match the original word for word add nothing. You can drop exact duplicates before searching, which saves calls. Near-duplicates are harder to detect and are usually left alone, because fusion handles them without harm.
A badly drifting variant is worse. If the model writes a query about something the user never asked, its results enter the merged list and can push out good passages. The original query's lists are your anchor. Two ways to reduce this risk:
- Keep the original query in the set, as the code does.
- Weight the original list more heavily during fusion if your evaluation shows variants adding noise.
Failures of the model call
The LLM call can fail or return an empty string. In that case variants is an empty list, and the function falls back to searching with the original question alone. Because of this, multi-query expansion degrades to ordinary retrieval when the model misbehaves. Keep that property if you change the code.
Mixing retrieval types
You can send the same variants to both a vector index and a BM25 index. Each search yields a ranked list, and all lists go into the same fusion step. This is a convenient way to combine keyword and semantic search, since fusion uses only ranks and does not need comparable scores.
Common errors
| Problem | Symptom | Fix |
|---|---|---|
| Variants are near-copies | Few new documents appear beyond the original search | Ask explicitly for *different* queries and different angles; show an example in the prompt |
| Numbered or bulleted output | Queries start with "1." or "- " and match poorly | Say "no numbering" in the prompt and strip list markers when parsing |
| Too many lines returned | Cost grows and extra queries are noisy | Slice to `n` after parsing |
| Original question dropped | Precise questions get worse results | Always search with the original too |
| Sequential searches | Latency grows with each variant | Run searches concurrently |
| Variant changes the meaning | Irrelevant passages reach the generator | Tell the model to keep names and constraints; check variants in logs |
Log the generated variants with each request. When retrieval quality drops, the variants are the first place to look.
Cost
Each request now costs one extra LLM call and n + 1 searches instead of one. The LLM call is usually the larger share of the added latency, because it is generation, not lookup. Use a small, fast model for variant generation. Writing search queries is an easy task, and the answer model is not needed for it.
The next chapter looks at the merging step in detail: why reciprocal rank fusion works, what the constant k does, and how ties and weights behave.
Exercise
A user asks, "Why is my build slow?" Your documents use the terms "compilation time", "CI pipeline duration" and "cache misses". Using multi_query_search with n=3, you notice that the final results are almost the same as the results of the original query alone. Name two likely causes and one change for each.
Show answer
First, the variants may be near-duplicates of the original (for example "Why is my build so slow?"), so they retrieve the same documents. Change the prompt to require different queries covering different angles, and give the model the vocabulary style of your corpus. Second, the generated variants may not be reaching the search at all, for example because parsing keeps numbering such as "1." or the model returns one long line, so variants holds a single odd string. Log the variants, fix the "one per line, no numbering" instruction and strip list markers when parsing. In both cases, checking the logged variants against the retrieved document ids shows which cause applies.
Exercise
In the demo output ['d2', 'd1', 'd3', 'd4', 'd6'], document d3 appears even though only one list contained it, and d5 is missing even though it also appeared in only one list. Why does d3 rank above d5, and what would happen to d5 if you used top_k=6?
Show answer
d3 was first in its list, which gives it a score of 1/61. d5 was third in its list, which gives it 1/63. d3 therefore scores higher. With top_k=6, each search would return up to six results from the same stub index, and the fused list is cut to six. Fusion would then give six entries: d2, d1, d3, d4, d6 and d5, in that order, so d5 would appear last.