---
title: "Query Rewriting & HyDE for RAG: Multi-Query, Step-Back (Code)"
description: "Turn what users type into what retrievers need: rewrite chat questions into keyword queries with the right date, run multi-query search merged with RRF, use HyDE for vector search, and step-back questions for why-questions. Python, with real model outputs."
category: "guides"
url: https://keirolabs.cloud/blog/query-rewriting-hyde
published: 2026-11-24
updated: 2026-11-24
---

# Query rewriting for RAG and search agents: HyDE, multi-query and step-back, with tested prompts

## The 60-second version

**Query rewriting turns what the user typed into what the retriever needs.** Users ask "does it support the new caching thing yet?". A search engine or vector index needs "Next.js Cache Components Vercel support". Four techniques cover most cases:

| Technique | What it does | Best for |
|---|---|---|
| **Rewrite for search** | Resolves pronouns from the chat, turns a question into 2–8 keyword queries, adds the date when it matters | Web search in chat apps and agents |
| **Multi-query** | Generates several differently-angled queries, retrieves for each, merges with RRF | Vague or broad questions |
| **HyDE** | Writes a hypothetical answer and embeds *that* instead of the question | Vector search where questions and documents look different |
| **Step-back** | Asks a more general question about the underlying concept | "Why" questions that need background |

**Each costs one small LLM call before retrieval.** All the prompts below were run on a real model; the outputs shown are what came back.

## Why rewrite queries at all?

**Because questions and documents don't look alike.**

- **Conversations use pronouns.** "Does *it* support…" means nothing to a search engine without the chat history.
- **Questions are phrased as questions.** Documents are phrased as answers. In embedding space, a question can sit closer to other questions than to the passage that answers it.
- **Users don't know the right terms.** "The new caching thing" is "Cache Components".
- **Dates go stale.** In our logs of 163 answers from OpenAI models with web search, 10% of the queries the models wrote added an old year the user never asked for ([grounding AI agents](/blog/grounding-ai-agents-web-search)). A rewrite step that knows today's date fixes that.

## Technique 1: rewrite for web search

**The most useful rewrite for chat apps and agents:** resolve references from the conversation, produce short keyword queries, and add the current year only when the question is about something recent.

```python
import json

def rewrite_queries(question: str, history: str = "", today: str = "2026-11-24", n: int = 3) -> list[str]:
    prompt = f"""Today is {today}. Rewrite the user's latest question into {n} web search queries.
Rules: 2 to 8 words each; keyword style, not sentences; resolve pronouns using the conversation;
include the current year only if the question is about something recent; each query should cover a different angle.
Return only a JSON array of strings.

Conversation so far:
{history or "(none)"}

Latest question: {question}"""
    text = llm(prompt).strip()
    text = text[text.find("["): text.rfind("]") + 1]          # tolerate prose around the JSON
    return [q for q in json.loads(text) if isinstance(q, str)][:n]
```

`llm()` is any function that sends a prompt to a model and returns the text. A small, fast model is enough for this step.

**What came back** for the history "I'm deploying Next.js on Vercel" and the question "does it support the new caching thing yet?":

```text
['Vercel Next.js caching support 2026',
 'Next.js Cache Components use cache Vercel',
 'Vercel new caching features rollout']
```

**"It" became Vercel, "the new caching thing" became Cache Components, and the year was added because the question is about something new.** None of those three queries could come from the raw question alone.

## Technique 2: multi-query with rank fusion

**Run all the rewritten queries, then merge the result lists with reciprocal rank fusion (RRF).** A page that ranks well for several phrasings rises to the top. A page that only one phrasing found still gets in.

```python
from concurrent.futures import ThreadPoolExecutor

def rrf_merge(result_lists: list[list[dict]], k: int = 60) -> list[dict]:
    scores, pages = {}, {}
    for results in result_lists:
        for rank, r in enumerate(results):
            scores[r["url"]] = scores.get(r["url"], 0) + 1 / (k + rank + 1)
            pages.setdefault(r["url"], r)
    return [pages[u] for u in sorted(scores, key=scores.get, reverse=True)]

def multi_query_search(question: str, history: str = "") -> list[dict]:
    queries = rewrite_queries(question, history)
    with ThreadPoolExecutor(len(queries)) as pool:                 # run the searches in parallel
        lists = list(pool.map(search, queries))
    return rrf_merge(lists)[:10]
```

`search()` is your search call, returning `{title, url, snippet}` dicts. **Run the queries in parallel,** so three searches take about as long as one. There's more on when to fan out, and how far, in [query fan-out](/blog/query-fan-out), and on RRF itself in [hybrid search with BM25 and RRF](/blog/bm25-hybrid-search-reciprocal-rank-fusion).

## Technique 3: HyDE (hypothetical document embeddings)

**HyDE asks the model to write a plausible answer, then searches with the embedding of that answer instead of the question.** A fake answer looks like a real answer: same vocabulary, same structure. So it lands nearer the right passages in embedding space, even when its facts are wrong.

```python
def hyde(question: str) -> str:
    return llm(f"Write a short, factual-sounding paragraph (about 80 words) that answers this question, "
               f"as it might appear in documentation. If unsure, write it anyway; it is only used for retrieval.\n\n"
               f"Question: {question}")

# Then embed hyde(question) instead of question, and search your vector index with it:
# hits = index.search(embed(hyde(question)), k=10)
```

**What came back** for "How do I stop BM25 from favoring short documents?":

```text
BM25's length-norm component, controlled by the *b* parameter (default 0.75 in most
implementations), can bias scores toward shorter documents ... To reduce this bias, lower *b*
or set it to 0 to disable length normalization entirely. ...
```

**That paragraph uses the words the right documents use:** "length normalization", "the b parameter", "0.75". The original question contains none of them.

**When HyDE helps, and when it doesn't:**

- **Helps:** vector search over documentation, papers and knowledge bases, where questions are short and passages are long.
- **Less useful for web search engines.** They're keyword-driven and already good at questions, so rewriting into keyword queries (technique 1) does more.
- **Risk:** on topics the model knows nothing about, the fake answer can point retrieval in the wrong direction. Search with both the question and the HyDE text, and merge them with RRF.
- **Cost:** one LLM call (about 100 output tokens) plus one extra embedding per question.

## Technique 4: step-back questions

**For "why" questions, retrieve background as well as the specific case.** Ask the model for the general principle, retrieve for both questions, and answer from both.

```python
def step_back(question: str) -> str:
    return llm(f"Rewrite this question as a more general question about the underlying concept or principle. "
               f"Return only the question.\n\nQuestion: {question}")
```

**What came back** for "Why does my Postgres query with LIKE '%term%' ignore the index?":

```text
Why can't a database index be used efficiently when a query doesn't specify how the indexed value begins?
```

**The specific question finds forum threads about your exact query; the step-back question finds the explanation of how B-tree indexes work.** Together, the model can both diagnose the problem and explain it.

## Which technique should I use?

| Situation | Start with |
|---|---|
| Chat app or agent calling a web search API | Rewrite for search (always) |
| Vague or broad questions | Multi-query + RRF |
| RAG over your own documents with embeddings | HyDE, merged with the plain question |
| Troubleshooting and "why" questions | Step-back + the original |
| Latency-critical, simple lookups | No rewrite: send the question as-is |

**Measure before keeping any of them.** Run your real questions with and without the rewrite and compare whether the right page lands in the top 5 (there's a small harness in [how to choose a web search API](/blog/how-to-choose-web-search-api)). Then rerank the merged results if precision matters ([reranking search results](/blog/reranking-search-results)).

For the `search()` function, Keirolabs `/search/lite` returns title, URL and snippet for $0.03 to $0.10 per 1,000 on plans, fast enough to run three rewritten queries per question. New accounts get up to 2,000 free credits with no card ([get a key](https://platform.keirolabs.cloud/register)).
