Sub topic 2
Why the user's question is often a poor search query
This chapter assumes you have built a basic RAG pipeline (index, retrieve, generate). It also assumes you know roughly how embedding search and keyword search (BM25) rank documents, and that you can read Python. Later chapters cover the fixes. This one covers diagnosis: how to tell why a query failed to find the right passages.
Recap: where single-shot retrieval stops working
A basic pipeline takes the user's text, turns it into a vector or a keyword query, and returns the top-k passages. It then pastes them into a prompt. Every step assumes the user's text is a good search query. That assumption holds for short, self-contained questions that use the same words as the documents. It fails often enough in production to account for many "the model hallucinated" reports. In those cases the model had no relevant passage to work from.
When retrieval fails, the generator cannot recover. It either answers from memory or answers from irrelevant passages. So it is worth checking the query before blaming the prompt or the model.
The core mismatch
A user writes a question to get an answer from a person. A search index matches a query against stored text. These are different jobs, and the gap shows up in several ways.
| Failure mode | What the user typed | Why search fails |
|---|---|---|
| Vocabulary mismatch | "How do I get my money back for a flight?" | The documents say "reimburse" and "travel expenses". |
| Missing context | "What about its pricing?" | "its" only means something in the earlier turns of the conversation. |
| Multi-part question | "Compare the refund policy of plans A and B." | One query vector is a blend of two topics and matches neither well. |
| Wrong level of detail | "Why does error E4021 appear on v2.3.1?" | The answer is in a general troubleshooting section, not in a page about that exact version. |
| Question versus answer form | "What causes memory leaks in Node?" | Passages are written as statements, not as questions. |
| Underspecified or ambiguous | "Tell me about the policy." | Several policies exist, and the query names none. |
The sections below cover each one.
Vocabulary mismatch
Keyword search only matches tokens that appear in both the query and the document. If the user says "money back" and the document says "reimbursement", BM25 sees no overlap. Even a small spelling difference breaks matching: "reimburse" and "reimbursement" are different tokens unless the index applies stemming.
Embedding search handles many synonyms, because "money back" and "reimbursement" land near each other in vector space. It is not a full fix. Embedding models are weaker on rare identifiers, product codes, internal jargon, and abbreviations. They can also rank a generic passage about "refunds" above the specific one about "travel reimbursement".
The following script shows the keyword case. It is deliberately simple: lowercase, split into tokens, count shared tokens.
import re
DOCS = {
"d1": "To reimburse travel costs, submit an expense report within 30 days.",
"d2": "Employees may work remotely up to three days per week.",
"d3": "The VPN client must be installed before accessing internal systems.",
}
def tokens(text: str) -> set[str]:
return set(re.findall(r"[a-z0-9]+", text.lower()))
def overlap_search(query: str, k: int = 2) -> list[tuple[str, int]]:
query_tokens = tokens(query)
scored = [(doc_id, len(query_tokens & tokens(text))) for doc_id, text in DOCS.items()]
scored.sort(key=lambda pair: pair[1], reverse=True)
return scored[:k]
queries = [
"How do I get my money back for a flight?",
"submit expense report travel reimbursement",
]
for query in queries:
print(query, "->", overlap_search(query))The output is:
How do I get my money back for a flight? -> [('d1', 0), ('d2', 0)]
submit expense report travel reimbursement -> [('d1', 4), ('d2', 0)]The first query has zero overlap with every document, so the order is arbitrary. The second query finds d1 with a score of 4, even though "reimbursement" does not match "reimburse". The correct document was in the index in both cases. Only the wording of the query changed.
Missing conversation context
In a chat, the user's last message often depends on earlier turns. Consider this exchange:
- User: "Does the Pro plan include SSO?"
- Assistant: "Yes, SSO is included in Pro."
- User: "And what about its pricing?"
The search system receives only the third message. The word "its" carries no topic, and "pricing" alone matches every pricing page in the index. A top-k search for "And what about its pricing?" returns pricing passages for all products, or generic passages that happen to mention "about".
Passing the whole conversation as the query is not a good fix either. Long chat histories dilute the embedding with unrelated turns, and keyword search matches stray words from old turns. The usual approach is to rewrite the last message into one standalone question. The next chapters cover that.
Multi-part questions
A single embedding is a single point in vector space. A question such as "Compare the refund policy of plan A and plan B, and say which one allows partial refunds" mixes at least three needs: plan A's policy, plan B's policy, and partial refunds. The vector lands somewhere between them. The top-k may be filled with passages about one plan, leaving none for the other.
The symptom is easy to spot. The retrieved passages cover only part of the question, and the model answers confidently about the covered part. The fix is to split the question into sub-questions, each searched on its own (decomposition).
Some multi-part questions are also multi-hop. "Who manages the team that owns the billing service?" cannot be searched in one step, because the second search depends on the first answer. Here you must retrieve, read, and then search again.
Wrong level of detail
Queries can be too specific or too broad for the passages that hold the answer.
- Too specific: the user asks about error E4021 on version 2.3.1. The documentation has a general section on connection timeouts that explains the cause, but it never mentions that version. Exact-match terms in the query pull in changelog entries that mention E4021 and miss the explanation.
- Too broad: the user asks "How does caching work?" and the corpus has dozens of passages that mention caching in passing. The top-k fills with them, and none is the overview.
A step-back query addresses the first case by asking a more general question before searching. Longer, more specific queries or filters address the second.
Question form versus answer form
Embedding models are trained so that questions and their answers land near each other. Even so, a question and a passage that answers it are written differently. The question is short and interrogative. The passage is long, declarative, and full of detail. The query embedding may sit closer to other questions, headings, or FAQ titles than to the explanatory passage. This asymmetry is the reason for HyDE, which generates a hypothetical answer and searches with that.
Underspecified and unnecessary queries
Two more cases do not need a rewrite at all.
- The question is ambiguous ("Tell me about the policy"). No rewrite can add what the user did not say. The right behavior is usually to ask a clarifying question.
- The question does not need retrieval ("Thanks!", "Translate this sentence", "What is 15% of 80?"). Retrieval adds latency and can inject distracting passages. Routing, covered later, decides whether to search at all.
Diagnosing a failure
You can usually tell which failure you have by looking at the query, the retrieved passages, and the passage you expected to find. This flow is a practical order of checks.
The last branch matters. Not every retrieval failure is a query failure. If the query is clear, standalone, and uses the document's vocabulary, and the passage still does not appear, look at chunk size, metadata filters, the embedding model, or the ranker. Rewriting a good query only adds cost.
A practical way to find the failures in your data
- Collect 30 to 100 real questions from logs, including multi-turn conversations with their history.
- For each question, mark which passage or document should be retrieved. This is your reference set.
- Run your current retrieval and record whether the expected passage is in the top-k, and at which rank.
- For each miss, assign one failure mode from the table above.
- Count the modes. The most frequent one tells you which technique to build first.
If most misses are follow-up questions, start with conversational rewriting. If they are multi-part questions, start with decomposition. Applying every technique to every query is the most expensive option and often not the most accurate. Each added step costs one more model call and one more place for the query to drift from what the user meant. Chapter 14 returns to those costs.
Summary of what to carry forward
- A raw user question is written for a human, not for an index.
- The main failure modes are vocabulary mismatch, missing context, multi-part questions, wrong level of detail, and question versus answer form.
- Some inputs need a clarifying question or no retrieval at all.
- Diagnose before you fix, using a small labeled set of real questions.
Exercise
A user in a support chat asks "Does it work on Linux?" after a long discussion about the product "Orbit Sync". Keyword search returns results about Linux kernels. Name the failure mode, say why it happens, and say what you should check first in your logs.
Show answer
This is missing conversation context. The query "Does it work on Linux?" contains no product name, because "it" refers to Orbit Sync from earlier turns. Search therefore matches "Linux" on its own. First check what string was actually sent to the retriever. If it is only the last message, the query needs to be rewritten into a standalone question such as "Does Orbit Sync work on Linux?"
Exercise
In the toy overlap search, the query "How do I get my money back for a flight?" scored 0 for every document. A teammate proposes adding a query rewriting step. Give one reason the step might help and one reason it might be the wrong first fix.
Show answer
It might help because the rewrite could introduce document vocabulary such as "reimburse", "travel", and "expense", which would give the keyword search tokens to match. It might be the wrong first fix if the corpus is searched with embeddings that already match "money back" to "reimbursement", or if the real problem is chunking or a metadata filter. Check the labeled failures first, and only add a rewrite step if the misses are caused by the query.