Sub topic 3
Text analysis: from raw text to searchable terms
This chapter assumes you know what an inverted index is: a map from each term to the documents that contain it. It also assumes you are comfortable reading short Python scripts. Here you will see how raw text becomes the terms stored in that index.
Why analysis matters
The index only matches terms that are identical strings. A document containing "Running" will not match a query for "run" unless both are reduced to the same form. Text analysis is the pipeline that does this reduction. It runs twice: once when a document is indexed, and once on the query text at search time.
The analysis pipeline
An analyzer is a chain of three stages.
- Character filters clean the raw string, for example by stripping HTML tags.
- A tokenizer splits the string into tokens, usually at whitespace and punctuation.
- Token filters change or drop tokens. Common ones are lowercasing, stop word removal, stemming, and synonym expansion.
A worked example
The script below implements a small analyzer. It lowercases and tokenizes, removes stop words, and applies a crude suffix stemmer.
import re
STOP_WORDS = {"the", "a", "an", "and", "of", "for", "in"}
def stem(token):
for suffix in ("ing", "ers", "er", "s"):
if token.endswith(suffix) and len(token) - len(suffix) >= 3:
return token[: -len(suffix)]
return token
def analyze(text):
tokens = re.findall(r"[a-z0-9]+", text.lower())
tokens = [t for t in tokens if t not in STOP_WORDS]
return [stem(t) for t in tokens]
print(analyze("The Running Shoes for Runners")) # ['runn', 'shoe', 'runn']
print(analyze("Run in the shoe")) # ['run', 'shoe']Notice that "running" and "runners" both become runn, so they match each other. But "run" stays run, so it matches neither. Real stemmers such as the Porter stemmer handle cases like this with many more rules, though they still make mistakes. This is the central trade-off of stemming: it raises recall (more matches) and lowers precision (some wrong matches).
Common choices and their costs
| Technique | What it does | Typical cost |
|---|---|---|
| Lowercasing | "Shoes" and "shoes" match | Rarely harmful. Acronyms lose their case. |
| Stop word removal | Drops words like "the" | Breaks phrase queries such as "to be or not to be". |
| Stemming | Cuts words to a root | Over-stemming merges unrelated words. |
| Lemmatization | Maps words to dictionary forms | Slower and needs language data. |
| Synonyms | Expands "sneakers" to "shoes" | Needs maintenance and can add noise. |
Common errors
- Using different analyzers at index time and query time. If the index stores stemmed terms but the query is not stemmed, "running" is searched as
runningand finds nothing. Most engines let you set separate index and search analyzers, so check both. - Analyzing fields that should match exactly. Product codes, email addresses, and categories should not be stemmed or split. Store them as exact-match fields, a distinction the mapping chapter covers.
- Ignoring language. A tokenizer built for English fails on languages written without spaces, such as Chinese or Japanese, and stop word lists differ per language.
- Changing the analyzer on a live index. Existing terms were produced by the old analyzer, so the index must be rebuilt to stay consistent.
Exercise
A user searches for "Shoes" and finds nothing, although a document contains "shoes". The index analyzer lowercases tokens, but the query is sent to a field that uses no analyzer. What is the cause, and how do you fix it?
Show answer
The index holds the lowercase term "shoes", but the query term "Shoes" is not lowercased, so the strings differ. Fix it by applying the same lowercasing analyzer to the query, for example by using a full-text match query on an analyzed field instead of an exact-term lookup.