Query expansion: add vocabulary without changing the question
查询扩展
Compare curated synonyms, pseudo-relevance drift and hypothetical document embeddings.
query-expansionJaguar: an animal, an engine, or both?
A reader wants jaguar habitat information. The query contains only “jaguar.” Two documents tie: one about an engine manual, another about rainforest conservation. If the system assumes its first result must be relevant, it may add “engine,” “repair” and “manual.” The second search can become more confident about the wrong meaning.
Query expansion introduces terms or representations intended to close a vocabulary gap. A curated vocabulary can connect “jaguar” with “Panthera onca.” Local methods can use initially retrieved documents. Generative methods can construct a hypothetical answer-like document and use its representation. Each method supplies a hypothesis about the information need, not a new source of truth. IIR distinguishes global vocabulary methods from relevance feedback and explains how blind feedback can drift. IIR, chapter 9
The unexpanded query is the baseline. Keep it in the evaluation: an expansion that improves easy examples may erase a precise product code, change a negation or choose the wrong sense of an ambiguous name.
Adding words changes the ranking geometry
Let q be nonnegative term weights and e an expansion vector over the same vocabulary. A simple rule is:
The weight controls influence, not factual reliability. We rank count vectors with cosine similarity:
Zero vectors receive score zero in our implementation. This is a transparent lexical baseline, not BM25 or a pretrained embedding model. Its scores change both through the dot product and through the query norm.
For pseudo-relevance feedback, select the first m results and pool their term counts, then normalize:
The initial ranking supplies the documents, so mistakes can reinforce themselves. A human positive label and membership in the initial top-m are different kinds of evidence. IIR, section 9.1.6
HyDE takes a different route. An instruction-following generator creates hypothetical documents; a contrastively trained document encoder maps them to vectors. Averaging N generated-document embeddings gives the paper’s basic estimator:
Search then compares that vector with real document vectors. The hypothetical text can contain incorrect details. Its role is to suggest relevance patterns; the real returned documents must still support the final answer. The v1 paper discusses averaging under an unambiguous-query assumption, making our jaguar example a useful warning about multiple senses. HyDE, sections 3.1–3.2
On a finite labeled collection, one simple outcome measure is:
R is the independently specified relevant set. Do not redefine relevance to match the expansion. Also inspect irrelevant results, latency and query classes harmed by the change; recall alone does not price every failure.
A reproducible wrong turn
Run the following with Python 3.12 and no external packages. The four documents are original synthetic examples. Only documents 1 and 2 are relevant to the stated animal information need. Equal scores break ties by ascending document index. The curated terms are supplied by the author, not produced by a language model.
"""Original lexical expansion and a deliberately ambiguous query."""
import json
import math
import re
from collections import Counter
DOCS = ['Jaguar engine repair manual', 'Panthera onca habitat rainforest', 'Jaguar habitat rainforest conservation', 'Engine repair manual parts']
def terms(text):
return Counter(re.findall(r'[a-z]+', text.lower()))
def cosine(a, b):
na = math.sqrt(sum(x*x for x in a.values())); nb = math.sqrt(sum(x*x for x in b.values()))
return sum(v*b.get(t, 0) for t, v in a.items())/(na*nb) if na*nb else 0.0
def rank(query, docs=DOCS):
return sorted([(cosine(query, terms(d)), i) for i, d in enumerate(docs)], key=lambda x: (-x[0], x[1]))
def expand(query, added, weight):
if not math.isfinite(weight) or weight < 0:
raise ValueError('finite nonnegative weight')
out = dict(query)
for t, value in added.items():
if not math.isfinite(value) or value < 0:
raise ValueError('invalid term weight')
out[t] = out.get(t, 0)+weight*value
return out
def pseudo(query, depth=1, weight=1.0):
if not isinstance(depth, int) or not 1 <= depth <= len(DOCS):
raise ValueError('invalid feedback depth')
chosen = rank(query)[:depth]; counts = Counter()
for _, i in chosen:
counts.update(terms(DOCS[i]))
norm = sum(counts.values())
return expand(query, {t: v/norm for t, v in counts.items()}, weight)
def recall(query, relevant=(1, 2), k=2):
return len(set(i for _, i in rank(query)[:k]) & set(relevant))/len(relevant)
def demo():
q = terms('jaguar')
# Curated disambiguation for an animal information need, not an LLM output.
dictionary = terms('panthera onca habitat rainforest')
trials = [('original', q), ('curated', expand(q, dictionary, 1)), ('pseudo', pseudo(q, weight=4))]
return dict(documents=DOCS, relevant=[1, 2], trials=[dict(name=n, weights=dict(v), ranking=rank(v), recall_at_2=recall(v)) for n, v in trials])
if __name__ == '__main__':
print(json.dumps(demo(), allow_nan=False))
The original query ranks documents 0 and 2 first, for Recall@2=0.5. Curated expansion with weight 1 ranks documents 1 and 2, reaching 1. Its leading cosine scores are about 0.894 and 0.671. Pseudo feedback takes document 0 and weight 4, producing weights 2 for “jaguar” and 1 each for “engine,” “repair” and “manual.” It ranks documents 0 and 3, reducing recall to zero.
That decline is constructed and hand-checkable; it is not a claim about average production performance. The example exposes how shared expansion terms can outweigh the original ambiguity. No HyDE generator or dense encoder runs here. To implement HyDE, replace the lexical mechanism with actual generation, encoding and retrieval, and log generated hypotheses separately from evidence.
One lexical pass scans the document terms and sorts N scores, costing O(T+N log N), where T is the total term work across documents and query interactions. Pseudo feedback requires an initial pass plus another pass with the expanded query. Model-based generation and encoding introduce additional costs that this standard-library example does not measure.
Protect the user’s intent
Expansion is useful when wording differs, but harmful when specificity is discarded. Preserve exact entities, numbers, dates and exclusions. For a genuinely ambiguous query, showing separate senses or asking a clarifying question may be more appropriate than averaging them into one vector. HyDE’s fictional document is especially unsuitable as a citation, even when it happens to be correct. HyDE
Build development and held-out query sets containing rare terms, ambiguity and vocabulary mismatch. Compare original-only, expanded-only and combined retrieval under the same candidate budget. If expansion consumes all slots, an otherwise useful original result can disappear. In a RAG system, score the downstream answer as well: better retrieval overlap does not guarantee better reasoning or citations.
Predict the changed results
- Explain. What makes pseudo feedback “pseudo”? Answer: The system assumes its top-ranked documents are relevant without obtaining relevance judgments. Its own first ranking supplies the labels implicitly.
- Calculate. Why does the expanded automotive document 3 beat animal document 2? Answer: The expanded query has norm square 7. Both documents have norm 2; document 3 shares three unit-weight automotive terms, scoring 3 divided by twice the square root of 7. Document 2 shares only “jaguar,” scoring 2 with the same denominator.
- Modify. Set the expansion weight to zero. What should the ranking do? Answer: Return to the original ranking, including the specified tie rule. Extra zero-valued dictionary entries must not alter the cosine scores.
- Investigate. What would establish that HyDE helps a particular collection? Answer: Run the actual generator and encoder on held-out queries, compare to the original-query baseline with the same corpus and search budget, and audit source-supported answers. A fluent hypothetical paragraph alone is no evidence of retrieval improvement.
Vocabulary, feedback and generated hypotheses
IIR supplies the classical vocabulary and feedback framework; HyDE moves the intermediate expansion into generated-document embedding space. Retrieval feedback develops update rules and evaluation leakage. RAG explains why retrieved documents and generated answers must remain conceptually separate.
Make a prediction, then check
Can a HyDE hypothetical document itself be cited as retrieved evidence?
Learning objectives
- Measure vocabulary recovery and diagnose an expansion that reinforces the wrong sense.
- Run the original example, explain its counterexample and identify the untested deployment assumptions.
Prerequisites & connections
Explore related knowledge →References
- An Introduction to Information Retrieval — online draft, April 1, 2009
Christopher D. Manning; Prabhakar Raghavan; Hinrich Schütze · 2009 - Precise Zero-Shot Dense Retrieval without Relevance Labels — arXiv v1
Luyu Gao; Xueguang Ma; Jimmy Lin; Jamie Callan · 2022
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-20 · Single AI author. Recorded source scopes (some exact source objects reused from earlier checks): Viewed physical PDF43/48/78/133/134/158/159/193; read PDF38/44/49/155/189/192 text. Inverted/positional indexes, Boolean merge, variable bytes, lexical vectors and evaluation; not a whole-book review. Read PDF 1 identity, 3–4 method/setup; viewed PDF 4. Use equation 7 averaging generated-document embeddings; generated text is not evidence. No model/API run. 5 paired equations and four explained exercises. Checked hand cosine, exact synthetic drift, zero-weight identity, pseudo-feedback normalization and unknown vocabulary. No HyDE model run. Additional IIR2009 reading: physical219 equation9.3 and clipping,221 centroid assumptions,223 separate-collection evaluation,224 pseudo/implicit feedback,226 and227 text below figure global vocabulary expansion. Existing Source preserved.
- Checked hand cosine, exact synthetic drift, zero-weight identity, pseudo-feedback normalization and unknown vocabulary. No HyDE model run.
- Four computed SVG variants per topic;12 numeric/geometry tests and42 responsive cases passed. Fourteen selected final captures directly viewed. Full article acceptance recorded separately.
Source locations checked:
- An Introduction to Information Retrieval — online draft, April 1, 2009 · Additional IIR2009 reading: physical219 equation9.3 and clipping,221 centroid assumptions,223 separate-collection evaluation,224 pseudo/implicit feedback,226 and227 text below figure global vocabulary expansion. Existing Source preserved.
- Precise Zero-Shot Dense Retrieval without Relevance Labels — arXiv v1 · Read PDF 1 identity, 3–4 method/setup; viewed PDF 4. Use equation 7 averaging generated-document embeddings; generated text is not evidence. No model/API run.
Related topics