Sub topic 5
Multi-query expansion: searching with several phrasings
This chapter assumes you have a working RAG pipeline (index, retrieve, generate), know what embeddings and BM25 search do, can call a language model with a text prompt, and can read Python. Multi-query expansion is one of the rewriting techniques from the previous chapters. It leads into rank fusion, which merges the results.
The problem it solves
A single query is one guess at how the answer is worded in your documents. If a user asks "How do I cancel my plan?" and the help article says "Ending your subscription", the match can be weak. This is vocabulary mismatch. Embeddings reduce it but do not remove it, and BM25 depends on shared words.
Multi-query expansion asks a language model for several different phrasings of the same question. You search with each phrasing and combine the results. A document that one phrasing misses may be found by another.
The working model
The technique has three steps:
- Ask the model for
nalternative search queries. - Run the original question and every variant through the same search function.
- Merge the ranked lists into one list.
The original question stays in the set. The variants add coverage, and the original protects you if the model writes poor variants.
Implementation
The merge step uses reciprocal rank fusion (RRF). Each document earns 1/(k+rank) from every list it appears in. Documents that several lists rank well rise to the top, and the scores from different searches never need to be comparable. The next chapter covers RRF in detail. Here it is as a function you can reuse.
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)
print(reciprocal_rank_fusion([["a", "b", "c"], ["b", "c", "d"]]))Document b is second in one list and first in the other, so it comes out on top. Now the expansion function. It takes the model and the search function as arguments, so you can plug in any provider or index.
from typing import Callable
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]Three details matter here:
- The prompt asks for one query per line with no numbering, so the output can be split by line. Without that instruction, you may get "1." prefixes that pollute the search.
- Blank lines are dropped and the list is cut to
n, because models sometimes return more or fewer lines than requested. - Each search returns
top_kdocument ids, and fusion trims the merged list back totop_k.
Common errors
- Near-duplicate variants. Three rewordings that differ by one word add cost but no coverage. Ask for variants that use different terms or angles, such as synonyms or a more technical phrasing.
- Drift. A variant may change the meaning of the question. Because the original is also searched and fusion rewards agreement, one off-topic variant usually cannot dominate, but several can.
- Duplicate passages as ids. Fusion only works if the same document gets the same id in every list. If you return raw text, make sure chunks are identical across searches.
- Too many variants. Each variant is one more search, and the model call itself adds latency. Start with three.
Exercise
In multi_query_search, why is the original question added to the list of queries instead of searching only with the model's variants?
Show answer
The original question guards against bad variants. If the model writes off-topic or empty variants, the original query's results still enter the fusion, and documents it ranks well are not lost.
Exercise
Two searches return ["a", "b"] and ["c", "a"]. With k = 60, which document ranks first after fusion, and why?
Show answer
Document "a". It scores 1/61 + 1/62 because it appears in both lists, which is higher than "b" (1/62) or "c" (1/61) alone.