How Lucene Analyzers Work

Analysis is the process Elasticsearch runs on a document’s text body before writing it into the inverted index. It breaks down into these steps:

  • Filter raw characters with a character filter (char filter)
  • Split the input into tokens according to specific rules with a tokenizer
  • Process those tokens further with token filters
  • Store the result in the index

After passing through an analyzer, the document ends up stored in Elasticsearch as an inverted index:

image-20220518124327931 AM

The analyzer in the diagram above has three parts:

  • char filter: character filter, the first step in processing a document body or search input. Official docs
  • tokenizer: splits text into terms and outputs a token stream.
  • filter: token filter, does further processing on the token stream. Token filters are not allowed to change the position or character offsets of each token. Official docs Common examples include:
    1. lowercase: converts all tokens to lowercase
    2. stop: removes stop words from the token stream
    3. synonym: adds synonyms into the token stream
    4. edge_ngram: re-tokenizes the token stream using specified minimum and maximum n-gram lengths

An analyzer combines character filters, a tokenizer, and token filters. The tokenizer splits a string of text into individual terms based on its rules or dictionary and outputs a token stream; each analyzer has one and only one tokenizer. Token filters transform the tokenized output (lowercasing, expanding synonyms, stripping stop words, mapping across languages, and so on), and an analyzer can have zero or more token filters.

Analyzers only apply to text fields. keyword fields are not analyzed or tokenized; they are used for exact matching and aggregations.

When analyzers run

  1. At index time, to analyze the document body for indexing
  2. At search time, to analyze the query input for searching

image-20220518120153972 AM