Text Analysis and Processing

7 min read

Introduction

The Problem: A user searches for "Spider-Man", but your database only has a document titled "Spiderman". Another user searches for "running shoes", but your product catalog lists them as "Running Shoe". In a standard relational database exact-match search, both users get zero results and leave your website forever.

The Solution: Text Analysis. Text analysis is the process of converting unstructured text into a structured format that is optimized for search. Elasticsearch does not just store your text as-is; it dissects it, cleans it, and organizes it into an inverted index so that searching is instantaneous and forgiving of human variations.

In this guide, we will break down exactly how Elasticsearch processes text under the hood, how you can control it, and how to debug it when your search results look like they were generated by a random number generator.


1. The Analysis Pipeline: Character Filters, Tokenizers, and Token Filters

The Definition

The Analysis Pipeline is an ordered sequence of operations that raw text passes through before it is indexed or searched. It consists of three distinct components: Character Filters, a Tokenizer, and Token Filters.

The Problem it Solves

Raw text is messy. It contains HTML tags, punctuation, capital letters, and grammatical variations. If we index text exactly as the user typed it, we force the searcher to guess the exact casing and punctuation. The pipeline standardizes the text on both ends (when indexing the document and when reading the user's search query).

How it Works (The Pipeline Flow)

Imagine you are running an industrial recycling plant. People throw bags of mixed trash (raw text) into the hopper. You need perfectly sorted, uniform cubes of recycled plastic (indexed terms) at the end. The pipeline is your assembly line.

Step 1: Character Filters (The Pre-processor)

Character filters receive the original raw text as a single string and modify it by adding, removing, or changing characters.

  • Industry Use Case: Removing HTML tags from scraped web content before indexing.
  • Example: The html_strip character filter transforms <p>Hello <b>World</b>!</p> into Hello World!.

Note: Character filters are rarely used unless you are dealing with very specific data formats like raw HTML or legacy system outputs.

Step 2: Tokenizer (The Slicer)

A Tokenizer receives the cleaned string from the character filter and breaks it down into individual chunks called tokens (usually words). An analyzer must have exactly one tokenizer.

  • Industry Use Case: Splitting a sentence into searchable words.
  • Example: The standard tokenizer splits text on word boundaries and removes punctuation. The string "Hello, World!" becomes ["Hello", "World"].

(If you use a basic whitespace tokenizer instead, "Hello, World!" becomes ["Hello,", "World!"]. Congratulations, your search for "Hello" now yields zero results because the comma hitched a ride. This is why the standard tokenizer is preferred.)

Step 3: Token Filters (The Refiner)

Token filters receive the stream of tokens from the tokenizer and can modify them (e.g., lowercasing), delete them (e.g., removing common "stop words" like "the" or "and"), or add them (e.g., injecting synonyms).

  • Industry Use Case: Making searches case-insensitive or linking variations of a word.
  • Example: The lowercase token filter takes ["Hello", "World"] and turns it into ["hello", "world"]. The synonym token filter might take ["sneakers"] and output ["sneakers", "shoes"].

2. Standard vs. Custom Analyzers

The Definition

An Analyzer is simply a pre-packaged analysis pipeline (combining the three components above). Elasticsearch comes with built-in analyzers, but also allows you to define your own.

The Problem it Solves

The standard analyzer works flawlessly for 80% of generic English sentences. But what if you are building a search engine for car parts, and your product IDs look like XYZ-998/A? The standard tokenizer will split this into ["XYZ", "998", "A"]. If a user searches the exact part number XYZ-998/A, they might get mismatched results. You need a way to tell Elasticsearch exactly how to read your specific data format.

The standard Analyzer

This is the default. If you do not specify an analyzer, Elasticsearch uses this.
It consists of:

  • Character Filter: None
  • Tokenizer: standard
  • Token Filter: lowercase

It is excellent for general text, articles, and descriptions.

Creating a Custom Analyzer

When industry standards demand specific search behaviors (like keeping part numbers intact, or handling email addresses), we build a Custom Analyzer.

Here is how you define a custom analyzer when creating an index. We will create an analyzer that strips HTML, splits by whitespace, and lowercases the text.

json
PUT /my-product-index
{
  "settings": {
    "analysis": {
      "analyzer": {
        "my_custom_html_analyzer": {
          "type": "custom",
          "char_filter": ["html_strip"],
          "tokenizer": "whitespace",
          "filter": ["lowercase"]
        }
      }
    }
  }
}

In industry practice, you define these settings once during index creation (or in an index template) and map your specific fields to use this custom analyzer.


3. Handling Languages and Stemming Basics

The Definition

Stemming is the process of reducing inflected or derived words to their root form (the "stem"). A Language Analyzer is a built-in analyzer specifically configured with grammatical rules (including stemming and stop-words) for a specific human language.

The Problem it Solves

Users are grammatically inconsistent. One user searches for "running", another searches for "ran", and another searches for "jumps". If your document contains "The quick brown fox jumped", a search for "jump" will fail under a standard analyzer because "jumped" != "jump".

How Stemming Works

Stemming algorithms are brutally efficient. They don't care about human feelings; they just chop off suffixes based on mathematical rules.

If you apply an English stemmer:

  • jumping, jumps, jumped ➡️ jump
  • foxes ➡️ fox

Because the text is stemmed during indexing and the user's query is also stemmed during search, "jumping" matches "jumped" perfectly because they both evaluate to "jump" behind the scenes.

The english Analyzer

Instead of building a complex stemming pipeline from scratch, the industry standard is to use Elasticsearch's built-in language analyzers.

The english analyzer includes:

  1. Standard Tokenizer
  2. English Stop Token Filter: Removes "a", "an", "and", "the", etc.
  3. Lowercase Token Filter
  4. English Stemmer Token Filter

Warning / Funny Exaggeration: Stemmers can be overzealous. The standard English stemmer will ruthlessly chop "Organization" down to "organ". If you search for "Organizing", you might inadvertently return documents about church pianos or human livers. In highly specialized domains (like medical databases), standard stemming is often disabled in favor of rigorous dictionaries.


4. Testing Analyzers with the Analyze API

The Definition

The Analyze API is an administrative endpoint in Elasticsearch that allows you to pass a string of text and an analyzer, and returns exactly how Elasticsearch breaks that text down into tokens.

The Problem it Solves

Search is failing. You mapped a field, indexed a million documents, and your search for "Wi-Fi" is returning zero results. You stare at your custom analyzer configuration, but JSON doesn't speak. You need to look inside Elasticsearch's brain to see what tokens it is actually generating.

Industry Practice: Debugging with _analyze

Before you apply an analyzer to a massive production index, you test it using the _analyze API. This is the single most frequently used tool for search relevance engineers.

You can run this directly in Kibana Dev Tools:

json
POST /_analyze
{
  "analyzer": "standard",
  "text": "The 2 QUICK Brown-Foxes jumped over the lazy dog's bone."
}

The Output:
Elasticsearch will respond with an array of the exact tokens it generated.

json
{
  "tokens": [
    {
      "token": "the",
      "start_offset": 0,
      "end_offset": 3,
      "type": "<ALPHANUM>",
      "position": 0
    },
    {
      "token": "2",
      "start_offset": 4,
      "end_offset": 5,
      "type": "<NUM>",
      "position": 1
    },
    {
      "token": "quick",
      "start_offset": 6,
      "end_offset": 11,
      "type": "<ALPHANUM>",
      "position": 2
    },
    {
      "token": "brown",
      "start_offset": 12,
      "end_offset": 17,
      "type": "<ALPHANUM>",
      "position": 3
    },
    {
      "token": "foxes",
      "start_offset": 18,
      "end_offset": 23,
      "type": "<ALPHANUM>",
      "position": 4
    }
    // ... rest of the tokens
  ]
}

What to look for in the output:

  • token: The actual string that gets saved in the inverted index. This is what you search against. Notice "Brown-Foxes" became "brown" and "foxes".
  • position: The order of the words. This is heavily used under the hood for "Phrase Searches" (e.g., matching words that are exactly next to each other).
  • start_offset / end_offset: The character positions in the original string. Used for highlighting the matched words in the search results UI.

If you ever wonder "Why didn't my document match?", throw the user's query and the document's text into the _analyze API. If the token values don't match, you've found your problem!


References & Further Reading

Challenge

You are an Elasticsearch engineer tasked with creating a robust search experience for user-submitted product reviews. The raw review text often contains HTML markup, inconsistent casing, and common English 'stop words' (e.g., 'a', 'the', 'is') that add noise to search queries.

Your goal is to construct the JSON request body for a POST /_analyze API call to test an ad-hoc analysis pipeline that correctly processes this type of text.

Requirements:

  1. The analysis pipeline must process the text in the following sequence:
    • First, strip all HTML elements from the input text.
    • Next, use the standard tokenizer to break the text into tokens.
    • Finally, apply two token filters in order: convert all tokens to lowercase, and then remove standard English stop words.
  2. Use the following sample text for the analysis: "<p>This is a WONDERFUL product! I love it.</p>"

Construct a single JSON object that represents the complete request body for this _analyze operation.

Expected result

A valid JSON object representing the request body for the Elasticsearch _analyze API. The object must define a custom analysis pipeline with:

  • A char_filter array containing the "html_strip" filter.
  • A tokenizer field set to "standard".
  • A filter array containing "lowercase" and "stop" token filters, in that specific order.
  • A text field containing the exact sample text provided in the instructions.
json

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.