Search Tutorials
--Ads--Multi-Query Retrieval
Generate several versions of a question and merge their results.
A single query is one point in embedding space. If the user's wording happens to sit far from the wording in your documents, retrieval misses. Multi-query retrieval asks an LLM to write several different versions of the question, searches with each, and merges the results. It casts a wider net and usually improves recall.
How it works
- Generate 3 to 5 alternative phrasings of the question, each from a slightly different angle.
- Run retrieval for the original question and every variation.
- Merge the result lists with Reciprocal Rank Fusion and keep the top k.
Implementation
from concurrent.futures import ThreadPoolExecutor
import numpy as np
from pydantic import BaseModel
import anthropic
from hybrid import rrf # from the hybrid search lesson
from rag_helpers import embed
client = anthropic.Anthropic()
class Variations(BaseModel):
queries: list[str]
def generate_variations(question: str, n: int = 4) -> list[str]:
response = client.messages.parse(
model="claude-opus-5-5",
max_tokens=800,
output_config={"effort": "low"},
messages=[{"role": "user", "content":
f"Write {n} different search queries that would help find documents answering "
"the question below. Use different wording and synonyms, and cover different "
"aspects of the question. Keep all names, numbers and codes.\n\n"
f"Question: {question}"}],
output_format=Variations,
)
return response.parsed_output.queries[:n]
def multi_query_search(question: str, vectors: np.ndarray, texts: list[str],
k: int = 5, per_query: int = 20) -> list[tuple[str, float]]:
queries = [question] + generate_variations(question)
query_vectors = embed(queries, query=True) # one batched embedding call
rankings = [list(np.argsort(-(vectors @ qv))[:per_query]) for qv in query_vectors]
return [(texts[i], score) for i, score in rrf(rankings)[:k]]
for q in generate_variations("Can my company pay for my broadband if I work from home?"):
print("-", q)
- home internet reimbursement for remote employees
- work from home expenses covered by the company
- broadband allowance remote work policy
- monthly internet cost reimbursement limit
Each variation reaches a different part of the vocabulary: "reimbursement", "allowance", "expenses", "internet" instead of "broadband". A document that uses any of those words now has a good chance of being retrieved.
Speed and cost
Multi-query adds one LLM call (for the variations) and several extra searches. Keep it fast by:
- generating all variations in one call with structured output, as above,
- embedding all queries in one batch,
- running searches against remote vector stores in parallel threads:
def parallel_search(search_fn, queries: list[str], k: int = 20) -> list[list]:
with ThreadPoolExecutor(max_workers=len(queries)) as pool:
return list(pool.map(lambda q: search_fn(q, k), queries))
Multi-query vs rewriting vs HyDE
| Technique | Generates | Main benefit |
|---|---|---|
| Query rewriting | One cleaner query | Removes noise; cheap |
| Multi-query | Several varied queries | Higher recall through vocabulary coverage |
| HyDE | A hypothetical answer | Matches answer-shaped documents |
Multi-query increases recall but can also pull in more loosely related chunks. Pair it with a reranker so that the extra candidates are filtered by true relevance before they reach the LLM.
Key takeaways
- Multi-query generates several phrasings of the question and fuses their search results.
- It improves recall when users and documents use different vocabulary.
- Generate variations in one call, embed them in one batch and search in parallel.
- Combine with reranking to keep precision high.