Lexical search

Also known as: keyword search · full-text search

On this page 7

Lexical search is a retrieval method that finds documents by matching the literal terms of a query against the terms stored in an index, then ranks the matches with a scoring function such as BM25 or TF-IDF. Also called keyword search or full-text search, it is the oldest and still the most widely deployed technique in retrieval & knowledge systems within artificial intelligence.

Lexical search does not interpret meaning; it relies on exact token overlap, corrected by text analysis such as lowercasing, stemming and stop-word removal. That limitation is also its strength: it is fast, transparent and precise for names, codes and rare terms, which is why modern RAG pipelines often combine it with semantic search in a hybrid design.

How lexical search matches and ranks documents

Lexical search works in two phases: indexing and querying. During indexing, an analyzer splits each document into tokens and normalizes them, and an inverted index records, for each term, the list of documents that contain it together with frequencies and positions. At query time, the same analyzer processes the query, the engine looks up each term’s postings list and scores every candidate document.

The score rewards terms that are frequent in the document but rare in the collection. BM25, the dominant ranking function, adds term-frequency saturation through the parameter k1 and document-length normalization through the parameter b, so that long documents do not win merely by repeating words. Typical defaults are k1 between 1.2 and 2.0 and b of 0.75.

The following table lists the main components of a lexical search engine and what each contributes.

ComponentFunctionTypical choices
TokenizerSplits text into termsWhitespace, Unicode word boundaries, n-grams
NormalizerUnifies forms of the same termLowercasing, accent folding
Stemmer or lemmatizerReduces words to a base formPorter, Snowball, dictionary lemmas
Inverted indexMaps terms to documentsPostings lists with positions
Scoring functionRanks candidate documentsBM25, TF-IDF, BM25F for fields
Query parserInterprets operators and phrasesBoolean, phrase, wildcard, fuzzy
Components of a lexical search engine

Keyword search supports several query forms beyond a bag of words, because the inverted index stores positions and term variants. These forms give users and applications precise control that embedding-based retrieval cannot offer directly.

Query typeExampleWhen it helps
Term queryinvoice overdueGeneral keyword lookup
Phrase query“out of memory”Exact error messages and quotations
Boolean queryrefund AND NOT subscriptionStrict inclusion and exclusion rules
Fuzzy queryrecieve~1Typos within a set edit distance
Prefix or wildcardkube*Partial identifiers and autocomplete
Field-boosted querytitle^3 bodyWeighting titles above body text
Common lexical query types

Each form has a cost. Wildcards with a leading asterisk and broad fuzzy matching expand into many index terms and can slow queries considerably on large collections.

Lexical search compared with semantic and hybrid retrieval

Lexical search and semantic search fail in opposite situations. Lexical retrieval misses documents that use synonyms or paraphrases, which is the vocabulary mismatch problem, while dense retrieval with embeddings can miss exact product codes, legal citations or rare names that the embedding model never learned to distinguish.

PropertyLexical searchSemantic searchHybrid search
Matching basisExact termsEmbedding similarityBoth, fused
Synonyms and paraphrasesWeak without expansionStrongStrong
Identifiers and rare termsStrongOften weakStrong
ExplainabilityHigh, visible term matchesLowModerate
Index costSmall, CPU onlyVectors, often GPU encodingBoth indexes
Domain shiftRobustNeeds suitable embedding modelRobust
Lexical, semantic and hybrid retrieval

Benchmarks such as BEIR show that BM25 remains a strong zero-shot baseline, frequently matching or beating dense retrievers on unfamiliar domains. For that reason, many production RAG systems run both retrievers and merge the lists with reciprocal rank fusion, then apply a cross-encoder reranker.

Learned sparse retrieval, such as SPLADE, sits between the two approaches. It keeps an inverted index and term-level scoring but uses a neural model to add weighted expansion terms, reducing vocabulary mismatch without dense vectors.

Configuring full-text search for retrieval pipelines

Good full-text search depends mostly on analysis and field design, not on the ranking formula. The analyzer must match the language and the content type, because a stemmer built for English prose can damage source code, chemical names or part numbers.

SituationRecommended choiceReason
Technical identifiersSeparate keyword field without stemmingPreserves exact codes
Multilingual contentLanguage-specific analyzers per fieldStemming rules differ by language
Short chunks in RAGLower b or tune length normalizationChunks have similar lengths
User typos commonFuzzy matching with edit distance 1Recovers misspellings cheaply
Domain synonyms knownCurated synonym list at query timeUpdates without reindexing
Configuration decisions

Teams should evaluate with labeled queries using Recall@k, mean reciprocal rank or NDCG before and after each change, because analyzer tweaks often help one query class and hurt another.

Limitations and common mistakes

Lexical search has predictable weaknesses that experienced engineers plan around rather than discover in production.

  • Vocabulary mismatch hides relevant documents that describe the same idea in different words.
  • Aggressive stop-word removal breaks queries such as “to be or not to be” or product names built from common words.
  • Over-stemming merges unrelated words, for example reducing “university” and “universe” to one stem.
  • Ignoring field boosts lets long body text outrank a short, exact title match.
  • Relying on lexical search alone in RAG reduces recall for conversational, paraphrased questions.

Query expansion, pseudo-relevance feedback and query rewriting by a language model can narrow the vocabulary gap, but each adds latency and may introduce topic drift, so they should be measured rather than assumed to help.

In simple terms

Lexical search is like the index at the back of a book. You look up a word, and the index tells you every page where that word appears. It finds words, not ideas.

If you search for “car”, it finds pages that say “car”. It may miss pages that only say “automobile”. On the other hand, it never confuses a part number or a person’s name with something similar. That is why many modern systems use keyword matching together with meaning-based search.

A practical example

An IT support team builds a RAG assistant over 40,000 internal tickets and runbooks. In early testing with dense retrieval only, the assistant often fails on questions such as “how do I fix error 0x80070005 on the print server”, because the embedding model treats different hexadecimal error codes as nearly identical. The correct runbook appears in the top 10 results for only about half of such queries.

The team adds a BM25 index over the same chunks, with a separate unstemmed field for error codes and hostnames, and merges both result lists with reciprocal rank fusion before a cross-encoder reranks the top 50. On a labeled set of 300 real questions, Recall@10 rises noticeably, with the largest gains on error-code and hostname queries, while paraphrased questions keep the quality that semantic search already provided.