When someone searches a library catalog, a website, or a collection of technical documents, the system must identify which items answer the information need and decide which to show first. Information retrieval (IR) is the discipline concerned with finding relevant information in a collection in response to a user’s information need, commonly expressed as a query.
Search differs from simply looking up a record by an exact identifier. A database can retrieve an article whose ID equals 42, whereas a search engine must decide whether an article about vector representations is relevant to a query such as “how computers represent word meanings.” The second task involves uncertain matches and ranking.
Start with a simple example
Suppose a PlainCS learner types “how does a computer turn words into numbers?” The exact phrase might not occur in an article titled Text Processing, Tokenization, and Embeddings. A useful search engine must still find that article and place it above pages about unrelated numbers.
A search system typically performs two jobs. Retrieval finds a manageable set of plausible documents. Ranking orders those candidates by estimated relevance. In some designs, both jobs happen in a single step; in others, they are separate stages.
Consider three documents:
- A: “Tokens and embeddings represent text numerically.”
- B: “Matrices represent numerical datasets.”
- C: “Web servers respond to HTTP requests.”
For the query “text embeddings,” a basic keyword system could score A highest because it contains the important query terms. A semantic system could also match a paraphrase such as “word vectors” even when the exact words differ. Neither approach guarantees relevance, and semantic matching may introduce surprising false positives.
Precision asks whether returned results are relevant. Recall asks whether relevant results were found at all. A website with perfect precision on one article might still have poor recall if it misses five other useful articles. This is why search quality needs more than a single example query.
1. The information retrieval problem
A typical search system has four essential elements:
- Corpus: The collection to be searched, such as web pages, articles, product descriptions, or documents.
- Document: An individual retrievable item. A document can be text, an image, a passage, or another indexed unit.
- Query: The user’s expression of an information need.
- Relevance: The extent to which a result satisfies that need in its particular context.
A retrieval system returns a ranked list of documents rather than necessarily a single correct answer. Relevance may depend on subject matter, freshness, language, reading level, access permissions, and the intent behind the query.
For example, a PlainCS search for gradient descent learning rate should generally rank an explanation of learning rates above an article that mentions those words only in passing.
Search versus recommendation
| Aspect | Search | Recommendation |
|---|---|---|
| Primary input | An explicit query or information need | User, item, and contextual signals |
| Main task | Find information relevant to the query | Suggest items likely to be useful |
| Typical output | Ranked search results | Ranked suggested items |
| Example | Find articles about backpropagation | Suggest backpropagation after studying derivatives |
The techniques overlap. Both systems may use candidate generation, embeddings, ranking models, and feedback signals.
2. Search system architecture
A practical search engine commonly separates index construction from query processing.
Index time: Collect documents, extract relevant content, normalize or tokenize text as appropriate, attach metadata, and construct one or more indexes.
Query time: Interpret the query, find eligible candidates, calculate relevance signals, rank candidates, and present results. Many systems use a fast first-stage retriever followed by a more expensive reranker.
3. Text processing and indexing
3.1 Tokenization and normalization
Text is often divided into tokens, such as words or subwords. Processing choices may include lowercasing, handling punctuation, and language-specific normalization.
These choices are not universally beneficial. Removing stop words can damage phrase meaning, and stemming can merge terms that users intended to distinguish. Search processing should match the language and retrieval task.
3.2 Inverted indexes
An inverted index maps each indexed term to the documents containing it. It can also store term frequency, positions, and field information.
Consider three short documents:
| Document | Text |
|---|---|
| D1 | neural network training |
| D2 | gradient descent training |
| D3 | neural network architecture |
A simplified index contains:
| Term | Matching documents |
|---|---|
| neural | D1, D3 |
| network | D1, D3 |
| training | D1, D2 |
| gradient | D2 |
| descent | D2 |
| architecture | D3 |
A query for neural training can find D1 by intersecting the relevant posting lists. Real indexes use compact data structures and richer scoring information to support large corpora efficiently.
3.3 Document granularity and metadata
Indexing a whole book as one item differs from indexing its chapters or passages. Smaller passages may be more precise but can lose surrounding context. Metadata such as title, category, publication date, access level, and language can support filtering and ranking.
A search engine must enforce access controls before showing restricted results or leaking their snippets. Relevance alone does not grant permission to view a document.
4. Keyword retrieval: Boolean search, TF-IDF, and BM25
4.1 Boolean retrieval
Boolean retrieval uses operators such as AND, OR, and NOT to specify exact matching conditions. It is useful for precise filtering, but it does not by itself explain which of several matches should appear first.
4.2 Term frequency and inverse document frequency
Term frequency (TF) reflects how often a term appears in a document. Inverse document frequency (IDF) gives greater weight to terms appearing in fewer documents.
One common smoothed IDF convention is:
Here is the number of documents and is the number containing term . Different implementations use different definitions and smoothing conventions.
TF-IDF combines term frequency with inverse document frequency. A document’s TF-IDF weights can be compared with the query using cosine similarity. Common words contribute less than relatively discriminative words.
4.3 BM25
BM25 is a widely used lexical ranking function that combines term matches, term rarity, term-frequency saturation, and document-length normalization.
A common form is:
where is the frequency of term in document , is the document length, is average document length, and and control saturation and length normalization. Some versions also account for query term frequency, and IDF definitions vary.
BM25 is a strong starting point because it is efficient and often works well when query and document wording overlap. Its main weakness is a vocabulary mismatch: a relevant document can use different words from the query.
5. Semantic search and dense retrieval
Semantic retrieval attempts to match meaning rather than relying only on exact keyword overlap. An embedding model maps a query or document into a numerical vector. Similarity between those vectors is used as a retrieval signal.
For vectors and , cosine similarity is:
For example, a query for “how models adjust weights” could retrieve an article about backpropagation and optimization, even if the words differ.
In a bi-encoder system, queries and documents are embedded separately, allowing document vectors to be computed in advance. A cross-encoder instead examines the query and candidate document together and can provide a richer relevance estimate, usually at a greater computation cost.
Dense retrieval has limitations: models can miss exact identifiers, confuse related but distinct concepts, and reflect weaknesses in their training data. Mathematical similarity is not a guarantee of factual correctness or task relevance.
Approximate nearest-neighbor search
A small corpus can compare each query vector against every document vector. Larger collections often use an approximate nearest-neighbor (ANN) index to find highly similar vectors without exhaustively scanning all of them. ANN systems trade some retrieval completeness for speed and resource efficiency.
6. Hybrid retrieval and reranking
Hybrid search combines complementary retrieval signals, such as BM25 keyword matches and embedding similarity.
A common pipeline is:
- Retrieve a set of candidates using lexical search.
- Retrieve another set using vector similarity.
- Merge and deduplicate the candidate sets.
- Combine ranks or scores, taking score-scale differences into account.
- Rerank the strongest candidates with a more precise model or task-specific rules.
- Apply final eligibility and presentation constraints.
One rank-based fusion method is reciprocal rank fusion (RRF):
Here is the set of ranked lists, and is a positive constant. A document present in several high-ranked lists receives a larger combined score. This method avoids directly comparing raw BM25 and vector scores, whose scales may be incompatible.
Hybrid search is especially useful when a collection contains both exact technical terms and natural-language explanations.
7. A working Python example: TF-IDF search
This example implements a small local search engine using scikit-learn. It extracts TF-IDF features from article descriptions, ranks by cosine similarity, and prints the strongest matches.
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
articles = [
("Vectors and Matrices", "Vectors matrices dimensions and linear algebra"),
("Gradient Descent", "Optimization learning rates loss and gradients"),
("Neural Networks", "Neurons weights layers activation and training"),
("Backpropagation", "Chain rule gradients and neural network training"),
]
titles = [title for title, _ in articles]
documents = [description for _, description in articles]
vectorizer = TfidfVectorizer(lowercase=True, ngram_range=(1, 2))
document_matrix = vectorizer.fit_transform(documents)
def search(query: str, limit: int = 3):
query_vector = vectorizer.transform([query])
similarities = cosine_similarity(query_vector, document_matrix).ravel()
indices = similarities.argsort()[::-1]
return [
(titles[i], round(float(similarities[i]), 3))
for i in indices
if similarities[i] > 0
][:limit]
for title, score in search("neural network gradients"):
print(f"{title}: {score:.3f}")
Install the dependency with pip install scikit-learn. This code is suitable for a small collection; it is not a production search engine. It has no permissions, persistent index, incremental updates, typo handling, or evaluation dataset. The scores indicate similarity under this particular representation, not calibrated probabilities of relevance.
Note: If none of the query’s terms appears in the fitted vocabulary, this implementation returns no matches. Semantic search or suitable query expansion may help, but both should be evaluated rather than assumed to improve quality.
8. Evaluating search quality
An appealing ranking is not necessarily a correct ranking. Evaluation requires queries and relevance judgments, which describe which documents satisfy each information need.
Suppose a query has five truly relevant documents in the corpus. The system returns five results, three of which are relevant.
- Precision@5: , the fraction of the five retrieved results that are relevant.
- Recall@5: , the fraction of all relevant documents recovered among the first five.
Other widely used metrics include:
| Metric | Main interpretation |
|---|---|
| Precision@K | Proportion of the top results that are relevant |
| Recall@K | Proportion of all relevant documents found in the top |
| Mean Reciprocal Rank (MRR) | Rewards putting the first relevant result near the top |
| Mean Average Precision (MAP) | Averages precision at relevant-result ranks across queries |
| nDCG@K | Rewards relevant results appearing early, including graded relevance |
For graded relevance, normalized discounted cumulative gain (nDCG) compares the ranking’s discounted relevance gain with an ideal ranking. It is particularly useful when results can be highly relevant, partly relevant, or irrelevant.
Evaluation should also consider latency, index freshness, failure rates, accessibility, and permission correctness. Online experiments may examine whether users find satisfactory answers, but clicks alone are an imperfect measure of relevance.
Evaluation pitfalls
- Incomplete judgments: Unjudged documents should not automatically be treated as irrelevant in every evaluation design.
- Selection bias: Logs are influenced by the ranking previously displayed to users.
- Query mix: A benchmark must include common, rare, navigational, ambiguous, and difficult queries.
- Train-test contamination: Model development must not use the evaluation queries or judgments in ways that inflate reported performance.
- Aggregate-only reporting: Average scores can hide failures on important query groups.
9. Common limitations and engineering challenges
Vocabulary mismatch: Relevant content uses synonyms or alternative descriptions. Use suitable stemming, synonyms, embeddings, or hybrid retrieval when justified.
Ambiguity: A short query like python might refer to the programming language or the animal. Context and clarification can improve retrieval.
Freshness: Recently updated content may not appear until the index is refreshed. Updates and deletions must be propagated correctly.
Duplicate content: Near-identical pages can crowd the results. Deduplication and canonicalization help maintain useful diversity.
Spam and manipulation: Keyword stuffing, low-quality pages, and malicious documents can distort rankings. Apply quality checks without assuming any automated score is infallible.
Privacy and permissions: Search indexes and snippets can expose content that users are not authorized to access. Authorization must cover retrieval, ranking inputs, caches, and generated previews.
Cost and scale: Complex rerankers and large embedding indexes require compute and storage. Multi-stage retrieval balances quality against latency and operational cost.
10. Search on PlainCS: a practical design
For PlainCS, a sensible first version could work as follows:
- Index article titles, descriptions, headings, and body text.
- Store the article slug, category, publication state, and relevant metadata.
- Exclude unpublished articles from public search results.
- Use a conventional full-text index or BM25 for initial retrieval.
- Boost title matches modestly when they indicate a strong match.
- Display a short, accurate snippet and link to
/articles/<article-slug>. - Evaluate results with a small, curated set of genuine study queries.
- Add hybrid retrieval only if it addresses measured failures of keyword search.
For example, a query such as “why does a neural network overfit?” should surface Model Training, Overfitting, and Generalization, not merely the article with the largest number of occurrences of neural network.
A search result page should distinguish not yet published content from no matching published content in site management tools. In the public experience, inaccessible drafts should generally not appear as clickable results.
11. Relationship to retrieval-augmented generation
Retrieval-augmented generation (RAG) uses retrieved material as context for a generative model. Its retrieval stage can use any of the techniques described here: keyword search, semantic search, hybrid ranking, and reranking.
Good retrieval is necessary but not sufficient for a reliable RAG response. The generator must also use retrieved evidence faithfully, avoid unsupported claims, and handle conflicting or missing sources.
12. Related concepts
- Text Processing, Tokenization, and Embeddings introduces text representations.
- Recommendation Systems explains personalized candidate selection and ranking.
- Vectors and Matrices develops the mathematical language of vector representations.
- Evaluating Machine Learning Models introduces evaluation principles.
- Embeddings and Vector Search develops dense indexing and similarity retrieval further.
- Retrieval-Augmented Generation connects information retrieval with generative models.
13. References and further reading
- Manning, C. D., Raghavan, P., and Schütze, H. Introduction to Information Retrieval. Cambridge University Press, 2008.
- Robertson, S., and Zaragoza, H. “The Probabilistic Relevance Framework: BM25 and Beyond”. Foundations and Trends in Information Retrieval, 2009.
- scikit-learn: Working with text data.
- scikit-learn: TfidfVectorizer.
Related articles in
- AI Agents and Tool-Using Workflows — Learn agent goals, tool invocation, planning, state, permissions, and how to evaluate multi-step AI workflows.
- AI Development Tools: Git, Jupyter, and APIs — Learn how Git, Jupyter notebooks, Python environments, and APIs fit together in reproducible, secure artificial intelligence workflows.
- How AI Is Changing Theoretical Computer Science — AI is beginning to help researchers explore algorithms, mathematical structures, and formal proofs. Here is what it can do, what still needs human judgment, and why verification matters.