N-gram token filter
Forms n-grams of specified lengths from a token.
For example, you can use the ngram token filter to change fox to [ f, fo, o, ox, x ].
This filter uses Lucene’s NGramTokenFilter.
The ngram filter is similar to the edge_ngram token filter. However, the edge_ngram only outputs n-grams that start at the beginning of a token.
The following analyze API request uses the ngram filter to convert Quick fox to 1-character and 2-character n-grams:
GET _analyze
{
"tokenizer": "standard",
"filter": [ "ngram" ],
"text": "Quick fox"
}
The filter produces the following tokens:
[ Q, Qu, u, ui, i, ic, c, ck, k, f, fo, o, ox, x ]
The following create index API request uses the ngram filter to configure a new custom analyzer.
PUT ngram_example
{
"settings": {
"analysis": {
"analyzer": {
"standard_ngram": {
"tokenizer": "standard",
"filter": [ "ngram" ]
}
}
}
}
}
max_gram- (Optional, integer) Maximum length of characters in a gram. Defaults to
2. min_gram- (Optional, integer) Minimum length of characters in a gram. Defaults to
1. preserve_original- (Optional, Boolean) Emits original token when set to
true. Defaults tofalse.
The default maximum difference between max_gram and min_gram is 1.
index.max_ngram_diff.
To customize the ngram filter, duplicate it to create the basis for a new custom token filter. You can modify the filter using its configurable parameters.
The following request creates a custom ngram filter that forms n-grams of 3 or 4 characters.
PUT ngram_custom_example
{
"settings": {
"analysis": {
"analyzer": {
"default": {
"tokenizer": "whitespace",
"filter": [ "3_4_grams" ]
}
},
"filter": {
"3_4_grams": {
"type": "ngram",
"min_gram": 3,
"max_gram": 4
}
}
}
}
}