Inferensys

Glossary

Lexical Search

Lexical search is an information retrieval technique that finds documents based on the exact occurrence of query terms or their morphological variants, using algorithms like BM25 or TF-IDF.
Stylish WeWork-like workspace with hot desks and document wall, professional searching through enterprise knowledge base on a mounted ultrawide display, warm industrial pendants overhead.
GLOSSARY

What is Lexical Search?

Lexical search is a foundational information retrieval technique that matches documents to queries based on the explicit presence of words.

Lexical search is an information retrieval technique that finds documents based on the exact occurrence of query terms or their morphological variants, using statistical algorithms like BM25 or TF-IDF. It operates on the principle of literal keyword matching, analyzing term frequency, inverse document frequency, and document length to compute a relevance score. This approach forms the backbone of traditional search engines and database full-text search, providing fast, exact matches where terminology is precise and consistent.

While highly efficient and deterministic, lexical search is limited by its reliance on surface-level text matching. It cannot resolve synonyms or understand contextual meaning without explicit rules. Consequently, it is often combined with semantic search in a hybrid search architecture to balance recall and precision. In modern vector database infrastructure, lexical search provides the fast, filterable first-stage retrieval that narrows candidate sets before more computationally expensive semantic similarity calculations.

FOUNDATIONAL SEARCH PARADIGM

Key Characteristics of Lexical Search

Lexical search is the classical approach to information retrieval, finding documents based on the exact occurrence of query terms. It forms the bedrock of search engines and is defined by its reliance on text matching and statistical weighting.

01

Term-Based Matching

Lexical search operates on the principle of exact or morphological term matching. It retrieves documents containing the query words themselves or their linguistic variants (e.g., 'run', 'running', 'ran').

  • Core Mechanism: Algorithms scan an inverted index, a data structure mapping each unique term to a list of documents containing it.
  • Limitation: It cannot understand synonyms or conceptual meaning without explicit expansion rules. A search for 'automobile' will not match a document only containing the term 'car' unless a synonym dictionary is applied.
02

Statistical Relevance Scoring (TF-IDF & BM25)

Not all matches are equal. Lexical search uses statistical models to rank documents by estimated relevance.

  • TF-IDF (Term Frequency-Inverse Document Frequency): Scores a document based on:
    • Term Frequency (TF): How often a term appears in the document.
    • Inverse Document Frequency (IDF): How rare the term is across the entire corpus. Common words (e.g., 'the', 'is') are downweighted.
  • BM25 (Best Matching 25): A state-of-the-art probabilistic extension of TF-IDF. It improves upon it by introducing non-linear term frequency saturation and document length normalization, preventing very long documents from dominating results. BM25 is the modern benchmark for keyword search performance.
03

The Inverted Index

The inverted index is the fundamental, high-performance data structure that enables fast lexical search at scale.

  • Structure: It is a dictionary where each key is a unique vocabulary term (a 'token'). The value for each term is a postings list—a sorted list of document identifiers (DocIDs) where that term appears, often with positional information and term frequencies.
  • Query Execution: For a query like 'vector database', the system:
    1. Looks up 'vector' and 'database' in the index.
    2. Retrieves their respective postings lists.
    3. Performs a fast set intersection (for AND queries) or union (for OR queries) on the lists.
    4. Scores the resulting documents using BM25 or similar. This structure allows for sub-second retrieval over billions of documents.
04

Query Operations & Syntax

Lexical search supports precise, Boolean-like control over result sets through specific query syntax.

  • Boolean Operators: AND, OR, NOT (or -) for logical combinations (e.g., python AND (tutorial OR guide) NOT java).
  • Phrase Search: Quoting terms ("neural network") requires the exact phrase to appear in sequence.
  • Proximity Search: Finding terms within a specified distance of each other (e.g., "transformer model"~5).
  • Wildcards & Prefixes: Using * for wildcard matching (comp* matches 'computer', 'computation') or ? for single character substitution.
  • Fielded Search: Restricting search to specific metadata fields (title:"attention is all you need").
05

Text Preprocessing Pipeline

Before indexing, raw text undergoes a text analysis or tokenization pipeline to normalize terms. This standardization is critical for consistent matching.

  • Steps typically include:
    1. Tokenization: Splitting text into individual words/tokens.
    2. Lowercasing: Converting all characters to lowercase.
    3. Stop Word Removal: Filtering out extremely common words (e.g., 'a', 'the', 'and').
    4. Stemming/Lemmatization: Reducing words to their root form (e.g., 'running' → 'run', 'better' → 'good').
    5. Character Filtering: Removing punctuation, HTML tags, or diacritics (accents). The specific pipeline configuration directly impacts recall and precision.
06

Strengths vs. Semantic Search

Lexical search has distinct advantages and limitations compared to semantic search (vector-based).

  • Key Strengths:
    • Precise Matching: Excellent for known-item search, codes, IDs, and exact phrases.
    • Explainability: Results are directly traceable to term occurrences; scoring is transparent.
    • Speed & Efficiency: Inverted index lookups are extremely fast and computationally cheap.
    • Terminology-Sensitive: Ideal for domains with rigid, specific vocabularies (e.g., legal, technical documentation).
  • Key Limitations:
    • Vocabulary Mismatch: Fails on synonyms, paraphrasing, and conceptual search.
    • No Semantic Understanding: Cannot grasp intent or context behind the words. This is why modern hybrid search systems combine lexical precision with semantic understanding.
CORE RETRIEVAL PARADIGMS

Lexical Search vs. Semantic Search

A technical comparison of two fundamental information retrieval approaches, highlighting their underlying mechanisms, performance characteristics, and ideal use cases.

Feature / MechanismLexical SearchSemantic Search

Core Matching Principle

Exact term or morphological variant occurrence

Contextual meaning and conceptual similarity

Primary Algorithm

BM25, TF-IDF

Cosine similarity on dense vector embeddings

Query/Document Representation

Sparse vectors (e.g., bag-of-words)

Dense vectors (e.g., from transformer models)

Handles Synonyms & Paraphrasing

Handles Typos & Misspellings

Interpretation of Polysemy (multiple meanings)

Literal; cannot disambiguate

Contextual; can disambiguate based on surrounding text

Typical Latency

< 10 ms

10-100 ms (varies with index size & model)

Index Storage Overhead

Low to Moderate

High (stores full vector for each document)

Query Understanding Required

Embedding model inference

Ideal For

Precise keyword matching, legal document retrieval, code search

Conceptual search, question answering, recommendation systems

Commonly Paired With

Boolean filters, faceted search

Metadata filtering, hybrid search, reranking

KEYWORD-BASED RETRIEVAL

Common Lexical Search Algorithms

Lexical search algorithms form the foundation of traditional information retrieval by matching documents based on the exact words or their morphological variants present in a query. These algorithms assign relevance scores based on term frequency, document length, and collection statistics.

01

TF-IDF (Term Frequency-Inverse Document Frequency)

TF-IDF is a statistical weighting scheme that evaluates the importance of a word to a document within a collection. It is the product of two metrics:

  • Term Frequency (TF): How often a term appears in a document.
  • Inverse Document Frequency (IDF): A measure of how common or rare the term is across the entire corpus.

A high TF-IDF score indicates a term is frequent in a specific document but rare in the overall collection, suggesting it is a strong keyword for that document. It powers classic vector space models where queries and documents are compared as sparse vectors.

02

BM25 (Best Matching 25)

BM25 is a probabilistic ranking function and the de facto standard algorithm for modern keyword search. It refines TF-IDF by introducing non-linear term frequency saturation and document length normalization.

Key mechanisms:

  • Term Frequency Saturation: The benefit of additional occurrences of a term diminishes after a certain point.
  • Length Normalization: Penalizes or rewards documents based on how their length compares to the average document length in the collection.
  • Tunable Parameters: Includes constants k1 (term frequency scaling) and b (length normalization impact) for fine-tuning.

BM25 is robust, efficient, and forms the lexical component in most hybrid search systems.

03

Boolean Retrieval

Boolean retrieval is a model where documents are retrieved based on exact matches to query terms combined with logical operators AND, OR, and NOT. It uses an inverted index for efficient lookups.

Example Query: "vector AND database NOT graph" retrieves documents containing both "vector" and "database" but excludes any containing "graph".

Characteristics:

  • Provides precise, deterministic control over result sets.
  • Does not rank results by relevance; all matching documents are considered equally relevant.
  • Often used as a foundational filtering layer in more complex search pipelines.
04

The Inverted Index

An inverted index is the fundamental data structure that enables fast lexical search. It maps each unique term (or token) in a corpus to a postings list of documents containing that term.

Structure:

  • Dictionary: A lookup table of all unique terms.
  • Postings Lists: For each term, a sorted list of document identifiers (DocIDs), often with additional data like term positions or frequencies.

Operations:

  • Intersection (AND): Finds common DocIDs across multiple postings lists.
  • Union (OR): Merges DocIDs from multiple lists.
  • Difference (NOT): Removes DocIDs from one list present in another. This structure allows sub-second retrieval from collections containing billions of documents.
05

Query Expansion & Stemming

These techniques improve recall by matching documents containing variations of the query terms.

Stemming: A crude heuristic process that chops off word endings to reduce words to a common root form (e.g., "searching", "searched", "searches" → "search"). Algorithms like the Porter Stemmer are commonly used.

Lemmatization: A more sophisticated linguistic process that uses vocabulary and morphological analysis to return the base or dictionary form of a word (e.g., "better" → "good").

Query Expansion: Augmenting the original query with synonyms or related terms from a thesaurus (e.g., "car" also searches for "automobile") to capture relevant documents that don't contain the exact query keyword.

06

Sparse Vector Representations

In lexical search, documents and queries are often modeled as sparse vectors in a high-dimensional space where each dimension corresponds to a unique term from the corpus.

How it works:

  1. The vocabulary of the entire corpus defines the vector space (e.g., 100,000+ dimensions).
  2. A document vector has non-zero values only for the terms it contains, weighted by schemes like TF-IDF.
  3. Relevance is calculated using similarity measures between these sparse vectors, such as the cosine similarity.

This contrasts with dense vector representations used in semantic search, where dimensions encode latent semantic features and every dimension has a value.

LEXICAL SEARCH

Frequently Asked Questions

Lexical search is the foundational information retrieval technique for finding documents based on exact keyword matching. This FAQ addresses its core mechanisms, modern applications, and how it integrates with advanced semantic search systems.

Lexical search is an information retrieval technique that finds documents based on the exact occurrence of query terms or their morphological variants. It operates by analyzing the surface-level text of queries and documents, ignoring semantic meaning.

How it works:

  1. Tokenization & Normalization: The search engine breaks text into tokens (words), removes stop words (e.g., 'the', 'a'), and applies stemming or lemmatization (reducing 'running' to 'run').
  2. Indexing: An inverted index is built, mapping each unique term to a list of documents containing it and its position.
  3. Scoring & Ranking: When a query is issued, the engine retrieves candidate documents from the index and scores them using algorithms like BM25 or TF-IDF. These algorithms weigh terms based on their frequency in the document (TF) and their rarity across the corpus (IDF), promoting documents where query terms appear prominently but not too commonly.
  4. Result Return: Documents are returned in descending order of their relevance score.
Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.