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 basic SQL and REST knowledge. Here you will see how raw text becomes the terms stored in that map, and why the same process must run on queries.
Why analysis exists
An inverted index only matches terms that are exactly equal. If a document says "Running Shoes!" and the user types "run shoe", a naive index finds nothing. Text analysis is the pipeline that turns raw strings into normalized terms, so that text with the same meaning produces the same terms.
Analysis runs in two places:
- At index time, on each full-text field of each document.
- At query time, on the text the user typed.
The terms from both sides must line up. Most search bugs in this area come from the two sides using different analysis.
The analysis pipeline
An analyzer is a fixed sequence of three kinds of steps.
- Character filters rewrite the raw string before splitting. Examples are stripping markup, or mapping
&toand. - A tokenizer splits the string into tokens, which are the candidate terms.
- Token filters change, drop, or add tokens. Examples are lowercasing, removing stop words, stemming, and adding synonyms.
Tokenizing
The tokenizer decides where one term ends and the next begins. The simplest approach splits on anything that is not a letter or digit, which is what the regular expression in the earlier index example did. Real text is harder:
| Input | Naive split | Problem |
|---|---|---|
| `wi-fi router` | `wi`, `fi`, `router` | The user may search `wifi` or `wi-fi`. |
| `[email protected]` | `user`, `example`, `com` | The email address cannot be found as one unit. |
| `C++` and `C#` | `c`, `c` | Two different languages become the same term. |
| `3.5mm jack` | `3`, `5mm`, `jack` | The number is broken apart. |
| Chinese or Japanese text | one long token | There are no spaces to split on. |
Standard tokenizers follow Unicode word-boundary rules, which handle many of these cases. Languages without spaces need a dictionary-based or n-gram tokenizer. For identifiers such as SKUs, email addresses, and part numbers, the usual answer is a different field type, covered below, not a cleverer tokenizer.
Normalizing
Normalization makes superficial differences disappear. The common steps are:
- Lowercasing, so
Redandredmatch. - Accent folding, so
caféandcafematch. This is a trade-off, because in some languages the accent separates different words. - Unicode normalization, so that the same character written as one code point or as a base letter plus a combining mark compares equal.
Stop word removal drops very common words such as the and of. It used to save space. Modern engines usually keep stop words, because BM25 already gives them a low weight, and removing them breaks phrase searches such as "to be or not to be".
Stemming and lemmatization
Stemming cuts words down to a root form, so running, runs, and ran-like variants can share a term. A stem is not always a real word. A stemmer applies rules, for example removing -ing and -s. Lemmatization looks words up in a dictionary and returns the base form, so better becomes good. It is more accurate but slower and needs language data.
The code below is a deliberately small analyzer. It shows the pipeline shape, not production quality stemming.
import re
import unicodedata
STOP_WORDS = {"the", "a", "of"}
def fold_accents(text):
decomposed = unicodedata.normalize("NFD", text)
return "".join(c for c in decomposed if not unicodedata.combining(c))
def stem(token):
for suffix in ("ing", "es", "s"):
if token.endswith(suffix) and len(token) - len(suffix) >= 3:
return token[: -len(suffix)]
return token
def analyze(text, use_stemming=True, drop_stop_words=False):
text = fold_accents(text.lower())
tokens = re.findall(r"[a-z0-9]+", text)
if drop_stop_words:
tokens = [t for t in tokens if t not in STOP_WORDS]
if use_stemming:
tokens = [stem(t) for t in tokens]
return tokens
print(analyze("Running Shoes")) # ['runn', 'shoe']
print(analyze("run shoe")) # ['run', 'shoe']
print(analyze("Café des Shoes")) # ['cafe', 'd', 'shoe']The output shows the main weakness of stemming. running becomes runn, not run, so it does not match the query run. Production stemmers such as Porter and Snowball handle doubled consonants and many other rules. Stemmers also make two kinds of error:
- Over-stemming merges words that differ in meaning, such as
universityanduniversein some stemmers. - Under-stemming leaves related words apart, such as
ranandrun.
Stemming is a recall and precision trade-off. It raises recall, the share of relevant documents found, and it can lower precision, the share of results that are relevant.
Synonyms
Synonyms let sneakers match trainers. You can apply them at index time or at query time.
| Approach | Strength | Weakness |
|---|---|---|
| Index time | Queries stay cheap. | Changing the list means reindexing every document. |
| Query time | The list can change without reindexing. | Queries expand to more terms, and multi-word synonyms are harder to handle. |
Query-time synonyms are the more common choice, because synonym lists change often and reindexing is expensive.
Analysis in the mapping
Analysis is configured per field in the mapping. The fields in the product mapping from the topic show the two main choices.
PUT /products
{
"mappings": {
"properties": {
"name": { "type": "text" },
"category": { "type": "keyword" },
"price": { "type": "float" },
"in_stock": { "type": "boolean" }
}
}
}- A
textfield goes through the analyzer.Trail Running Shoesis stored as separate normalized terms. It supports relevance-ranked matching but not exact string matching. - A
keywordfield is stored as one unanalyzed term.footwearmatches onlyfootwear. It supports exact filters, sorting, and aggregations.
The same source value can need both. A product name usually needs to be searched as text and also sorted as a keyword. Engines support this with multi-fields, where one source value is indexed twice under different names and analyzers.
Inspecting what the analyzer does
You do not need to guess. Engines expose an analyze API that shows the terms produced for a given input. In Elasticsearch-style engines:
POST /_analyze
{
"analyzer": "english",
"text": "The Running Shoes of 2026"
}The response lists each token with its position. Use it whenever a document is not found when you expect it to be. Check what the document produced at index time, then what the query produced, and compare.
Common errors
- Different analyzers at index and query time. A document stemmed at index time cannot match an unstemmed query term. Engines allow a separate search analyzer, which is correct only for deliberate cases such as synonym expansion or autocomplete.
- Wrong language. An English stemmer applied to French text produces meaningless stems. Choose the analyzer by the field's language, and when content is mixed, store a language field and route accordingly.
- Changing the analyzer without reindexing. Existing documents keep the terms produced by the old analyzer, so the index and queries drift apart. An analyzer change is a schema change and needs a reindex.
- Treating identifiers as text. Order numbers and SKUs should be
keywordfields, possibly with a second analyzed field for partial matches. - Over-aggressive normalization. Stripping punctuation destroys
C++and.NET. Test with the actual vocabulary your users search for.
Decision criteria
Start with the engine's standard analyzer or its built-in analyzer for the content language. Add steps only when you can name a failing query that the step fixes. Each added filter is a decision that changes recall and precision, and each must be applied identically to every document, which makes it expensive to undo. Keep a small list of real user queries and run them after each analysis change.
Exercise
A user searches for Footwear and gets no results from { "term": { "category": "Footwear" } }, but the documents have the category Footwear. The category field is mapped as text. Why does the query fail, and what are two ways to fix it?
Show answer
A text field is analyzed, so the index stores the lowercased term footwear. A term query is not analyzed, so it looks for the exact term Footwear, which is not in the index. Fix it by mapping category as keyword, which stores the exact value (this requires a reindex), or by using a match query, which analyzes the query text the same way and finds footwear.
Exercise
Your index uses a stemmer. A user searches for organization and gets results about organs. What kind of stemming error is this, and what is one way to reduce it?
Show answer
This is over-stemming. The stemmer reduces unrelated words to the same stem, so they share a term. Options are using a lighter stemmer, using a lemmatizer, adding a protected-words list that the stemmer skips, or indexing an unstemmed copy of the field and boosting exact matches above stemmed ones.