Information retrieval: finding documents that meet the need
信息检索基础
Compare exact lexical matches and explicit synonym normalization against declared relevance.
information-retrievalThe right document uses a different word
A reader wants records about replacing a bicycle brake cable. The query is “bicycle brake cable.” In our fictional collection, one relevant record says “cycle stopping wire replacement,” so it shares no query words. Another says “car brake cable repair”: it shares two words but concerns the wrong vehicle. Matching words and meeting an information need are different tests.
Information retrieval connects a need to useful material in a collection. A practical system identifies documents, analyzes their content, builds a searchable representation, generates candidates and orders them for the reader. The query is a short expression of the need; the relevance judgment should refer to the need itself. The IIR textbook makes this distinction explicit in its evaluation chapter. IIR, section 8.1
For a small collection, a non-AI baseline is a complete scan. The example below uses nine invented text fragments, including an empty record and near-duplicates. IDs 0,4,5,7 are declared relevant to the repair need. These are authored labels, not user-study observations or judgments inferred from the retrieval score.
Decide what each stage promises
Our first ranker counts distinct query words present in a document. Q is a set, so repeating a query word does not increase its weight. Documents with zero overlap are omitted; equal scores use ascending document ID.
This score is neither a probability nor a truth judgment. The analyzer lowercases text and keeps ASCII letter sequences; it does not stem words or understand Chinese. Both document and query must use the same policy. Changing that policy changes the representation and may require rebuilding the index.
Let R be the declared set of relevant documents and L_k the returned prefix, of length at most k. We define precision at k with denominator k even when fewer documents are returned; an unused slot contributes no hit. Recall is undefined when R is empty.
Reciprocal rank instead rewards finding the first relevant document early. Here r* is its one-based rank in the entire returned list, not necessarily within the cutoff:
A two-stage system may rerank only a candidate pool C. No reordering can recover a document absent from C, which gives a useful stage-level ceiling:
The inequality becomes equality if the full pool is returned. A shorter displayed prefix can have lower recall still. Measure candidate coverage before blaming the reranker.
A synonym map that helps one need and hurts another
Run the self-contained program with Python 3.12; it needs only the standard library. Each document’s position in DOCUMENTS is its ID. The literal ranker is compared with file order and with an explicitly authored normalization map: cycle→bicycle, stopping→brake, wire→cable, replacement→repair. This is a vocabulary rule, not a learned semantic model.
import json,math,re
from collections import Counter,defaultdict
DOCUMENTS=(
'repair bicycle brake cable',
'bicycle brake adjustment guide',
'bicycle paint blue frame',
'car brake cable repair',
'cycle stopping wire replacement',
'repair bicycle brake cable cable cable',
'',
'brake cable bicycle repair',
'cell cycle stopping research',
)
def tokens(text):
if not isinstance(text,str) or len(text)>2000:raise ValueError('text of at most2000 characters required')
return re.findall(r'[a-z]+',text.lower())
def corpus(documents):
if not isinstance(documents,(list,tuple)) or not 1<=len(documents)<=100:raise ValueError('one to100 documents required')
return [tokens(d) for d in documents]
ALIASES={'cycle':'bicycle','stopping':'brake','wire':'cable','replacement':'repair'}
def rank(query,documents=DOCUMENTS,expand=False):
docs=corpus(documents);q=tokens(query)
def normalize(ts):return {ALIASES.get(t,t) if expand else t for t in ts}
q=normalize(q);scored=[(i,len(q&normalize(ts))) for i,ts in enumerate(docs)]
return [dict(doc=i,score=s) for i,s in sorted(scored,key=lambda x:(-x[1],x[0])) if s>0]
def evaluate(ranking,relevant,universe,k):
if type(k) is not int or not 1<=k<=100:raise ValueError('cutoff1..100 required')
if len(ranking)!=len(set(ranking)) or not set(ranking)<=set(universe) or not set(relevant)<=set(universe):raise ValueError('unique ranked IDs and relevance within the declared universe required')
top=ranking[:k];hits=sum(i in relevant for i in top)
return dict(precision_at_k=hits/k,recall_at_k=hits/len(relevant) if relevant else None,returned=len(top),relevant_total=len(relevant),hits=hits,reciprocal_rank=next((1/(i+1) for i,d in enumerate(ranking) if d in relevant),0.))
def demo():
universe=list(range(len(DOCUMENTS)));relevant={0,4,5,7};query='bicycle brake cable';results={}
ranks={'file_order':universe,'lexical':[v['doc'] for v in rank(query)],'normalized':[v['doc'] for v in rank(query,expand=True)]}
for name,order in ranks.items():results[name]=dict(ranking=order,cutoffs={str(k):evaluate(order,relevant,universe,k) for k in [1,2,3,4,6]})
ambiguous={}
for name,expand in [('literal',False),('normalized',True)]:
order=[v['doc'] for v in rank('cycle',expand=expand)];ambiguous[name]=dict(ranking=order,metrics=evaluate(order,{8},universe,2))
candidates=set(ranks['lexical'][:3]);ceiling=len(candidates&relevant)/len(relevant)
return dict(documents=list(DOCUMENTS),need='Find bicycle brake cable repair/replacement records.',query=query,relevant=sorted(relevant),results=results,ambiguous_cycle_need='Find the cell-cycle record, not bicycle records.',ambiguous_cycle=ambiguous,lexical_top3_recall_ceiling=ceiling,unknown_query=rank('quasar'),empty_query=rank(''),scope='Authored fragments and relevance labels; no human study or learned semantic retriever.')
if __name__=='__main__':print(json.dumps(demo(),indent=2,allow_nan=False))
At cutoff four, file order has precision and recall 0.25. Literal matching ranks 0,5,7,1 first, giving 0.75 for both. Normalization ranks 0,4,5,7 first and reaches 1 on this constructed need. All three have reciprocal rank 1 because the first result is relevant; RR alone misses the difference in completeness.
Now the need is the cell-cycle record, ID 8, and the query is “cycle.” Literal matching returns 4,8, retaining the relevant record within two slots. The same normalization map introduces bicycle records ahead of it; recall at two drops from 1 to 0. A synonym rule useful in one domain can conflate meanings in another.
The literal top-three candidate pool contains 0,5,7 and has recall ceiling 0.75. Permuting those IDs cannot find ID 4. Near-duplicates deliberately consume several slots here; our metric counts relevant document IDs, not distinct facts or diversity. A production evaluation may need both.
With T analyzed tokens and N documents, scanning costs O(T), followed by O(N log N) sorting; the simple implementation stores analyzed documents. The example is small enough to inspect every label. At larger scale, inverted indexes reduce query-time scanning, while BM25 offers a more detailed lexical score.
Evaluate the need, not the convenient proxy
NIST’s TREC overview describes evaluation using documents, questions, submitted rankings and pooled relevance judgments. This supports separating the retriever from the evidence used to judge it. The historical overview is not a specification for every present-day track. TREC
For an application, keep development queries apart from the final evaluation set. Include queries with no relevant document, ambiguous language, misspellings and changed vocabulary. Record unjudged documents separately; missing judgments are not proof of irrelevance. Compare quality at the actual display cutoff along with latency, index size, freshness and update cost. Apply permission filters before returning restricted material.
A curated lookup may be enough for exact product IDs; lexical ranking is a useful baseline for free text. Broader matching can improve candidate recall but introduce false positives. Use the observed failure to choose an intervention: vocabulary handling for a missed synonym, positional matching for a phrase, a better scorer for poor ordering, or refreshed data for an absent document.
Which part failed?
- A document contains every query word. Must it satisfy the reader’s need?
Answer: No. The car-repair fragment overlaps strongly with a bicycle-repair query but concerns the wrong vehicle. Relevance refers to the specified need.
- One relevant document is returned for a cutoff of four; two relevant documents exist. What are the two metrics under our convention?
Answer: P@4 is 1/4; recall at four is 1/2. Dividing precision by the one returned document would use a different metric and hide empty slots.
- Can reranking 0,5,7 achieve full recall for R=0,4,5,7?
Answer: No. All permutations retain only three of the four relevant IDs, so the maximum recall is 3/4. Candidate generation must add ID 4.
- Should the cycle→bicycle mapping be enabled for every query after it improves repair search?
Answer: No. It harms the declared cell-cycle need. Evaluate vocabulary rules across domains or apply context-dependent expansion, while keeping an untouched comparison set.
A reproducible comparison needs labels
The textbook explains retrieval representations and relevance-based evaluation; TREC illustrates shared evaluation infrastructure. The nine fragments, labels and numerical outcomes are original. This exercise establishes exactly what these rankers do on that fixture, not a measured gain on a public collection or a guarantee of user satisfaction.
Make a prediction, then check
A candidate pool misses one of four relevant documents. Can reranking that same pool recover full recall?
Learning objectives
- Separate the information need, query, candidate set, ranking and relevance judgment.
- Run the original small corpus and explain a failure case.
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 - Text REtrieval Conference (TREC) Overview
National Institute of Standards and Technology
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-20 · Single AI author. 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 opening through the described document/question, ranked-run pooling and judgment workflow; historical page, not a claim about every current track. 4 paired equations and four explained exercises. Need-relative relevance, cutoff denominators, synonym collision, empty-label handling and candidate recall ceiling independently checked.
- Need-relative relevance, cutoff denominators, synonym collision, empty-label handling and candidate recall ceiling independently checked.
- Four computed SVG variants per topic;10 numeric/geometry tests and30 responsive cases passed. Ten selected final captures directly viewed. Full article acceptance recorded separately.
Source locations checked:
- An Introduction to Information Retrieval — online draft, April 1, 2009 · 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.
- Text REtrieval Conference (TREC) Overview · Read opening through the described document/question, ranked-run pooling and judgment workflow; historical page, not a claim about every current track.
Related topics