Artificial Intelligence • AI Application Domains • 13 min read

Information Retrieval and Search

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:

  1. A: “Tokens and embeddings represent text numerically.”
  2. B: “Matrices represent numerical datasets.”
  3. 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

AspectSearchRecommendation
Primary inputAn explicit query or information needUser, item, and contextual signals
Main taskFind information relevant to the querySuggest items likely to be useful
Typical outputRanked search resultsRanked suggested items
ExampleFind articles about backpropagationSuggest 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.

A search architecture showing documents being processed into an index and a user query using that index to retrieve and rank results
High-level indexing and retrieval pipeline. Production systems also handle permissions, updates, logging, and failures.

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:

DocumentText
D1neural network training
D2gradient descent training
D3neural network architecture

A simplified index contains:

TermMatching documents
neuralD1, D3
networkD1, D3
trainingD1, D2
gradientD2
descentD2
architectureD3

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:

IDF⁡(t)=log⁡(N+1df⁡(t)+1)+1\operatorname{IDF}(t)=\log\left(\frac{N+1}{\operatorname{df}(t)+1}\right)+1

Here NN is the number of documents and df⁡(t)\operatorname{df}(t) is the number containing term tt. 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:

BM25⁡(D,Q)=∑t∈QIDF⁡(t)⋅f(t,D)(k1+1)f(t,D)+k1(1−b+b∣D∣avgdl⁡)\operatorname{BM25}(D,Q)=\sum_{t\in Q}\operatorname{IDF}(t)\cdot \frac{f(t,D)(k_1+1)}{f(t,D)+k_1\left(1-b+b\frac{|D|}{\operatorname{avgdl}}\right)}

where f(t,D)f(t,D) is the frequency of term tt in document DD, ∣D∣|D| is the document length, avgdl⁡\operatorname{avgdl} is average document length, and k1k_1 and bb 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 q\mathbf{q} and d\mathbf{d}, cosine similarity is:

cos⁡(q,d)=q⋅d∥q∥∥d∥\operatorname{cos}(\mathbf{q},\mathbf{d})= \frac{\mathbf{q}\cdot\mathbf{d}}{\|\mathbf{q}\|\|\mathbf{d}\|}

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.

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:

  1. Retrieve a set of candidates using lexical search.
  2. Retrieve another set using vector similarity.
  3. Merge and deduplicate the candidate sets.
  4. Combine ranks or scores, taking score-scale differences into account.
  5. Rerank the strongest candidates with a more precise model or task-specific rules.
  6. Apply final eligibility and presentation constraints.

One rank-based fusion method is reciprocal rank fusion (RRF):

RRF⁡(d)=∑r∈R1k+rank⁡r(d)\operatorname{RRF}(d)=\sum_{r\in R}\frac{1}{k+\operatorname{rank}_r(d)}

Here RR is the set of ranked lists, and kk 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.

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: 3/5=0.603/5=0.60, the fraction of the five retrieved results that are relevant.
  • Recall@5: 3/5=0.603/5=0.60, the fraction of all relevant documents recovered among the first five.

Other widely used metrics include:

MetricMain interpretation
Precision@KProportion of the top KK results that are relevant
Recall@KProportion of all relevant documents found in the top KK
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@KRewards 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:

  1. Index article titles, descriptions, headings, and body text.
  2. Store the article slug, category, publication state, and relevant metadata.
  3. Exclude unpublished articles from public search results.
  4. Use a conventional full-text index or BM25 for initial retrieval.
  5. Boost title matches modestly when they indicate a strong match.
  6. Display a short, accurate snippet and link to /articles/<article-slug>.
  7. Evaluate results with a small, curated set of genuine study queries.
  8. 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.

13. References and further reading

Related articles in

Image preview

Fit