# 3.3.5.Token Filters（词语过滤器）

**TokenFilters**（词元过滤器） 接受来自 [tokenizer（分词器）](http://www.apache.wiki/pages/viewpage.action?pageId=9405270) 的 **tokens** 流，并且可以修改 **tokens**（例如小写转换），删除 **tokens**（例如，删除 **stopwords**停用词）或添加 **tokens**（例如，同义词）。

**Elasticsearch** 提供了很多内置的**token filters**（词元过滤器），可以用于构建 [custom analyzers](https://www.elastic.co/guide/en/elasticsearch/reference/5.3/analysis-custom-analyzer.html)（自定义分词器）。

## Standard Token Filters（标准词元过滤器）

**standard**类型的词元过滤器规范化从**Standard Tokenizer（标准分词器）**&#x4E2D;提取的**tokens**。

**提示**：标准词元过滤器目前什么都不做。 如果在将来的版本中需要添加一些过滤功能，它将保留为占位符。

## ASCII Folding Token Filter（ASCII Folding 词元过滤器）

**asciifolding**类型的词元过滤器，将不在前127个ASCII字符（“基本拉丁文”Unicode块）中的字母，数字和符号Unicode字符转换为ASCII等效项（如果存在）。

例如：

```
"index" : {
    "analysis" : {
        "analyzer" : {
            "default" : {
                "tokenizer" : "standard",
                "filter" : ["standard", "asciifolding"]
            }
        }
    }
}
```

接受默认为**false**的**preserve\_original**设置，但如果为**true**，则将保留原始**token** 并发出 **folded token**。

例如：

```
"index" : {
    "analysis" : {
        "analyzer" : {
            "default" : {
                "tokenizer" : "standard",
                "filter" : ["standard", "my_ascii_folding"]
            }
        },
        "filter" : {
            "my_ascii_folding" : {
                "type" : "asciifolding",
                "preserve_original" : true
            }
        }
    }
}
```

## Flatten Graph Token Filter（Flatten Graph 词元过滤器）

**警告：**\
此功能是实验性的，可能会在将来的版本中完全更改或删除。**Elastic**将采取最大的努力来解决任何问题，但实验功能不受**SLA**官方功能的支持。

**flatten\_graph** 词元过滤器接受任意图形 **token** 流，例如由**Synonym Graph Token Filter** 产生的图形**token**流，并将其平坦化为适用于索引的单个线性标记链。

这是一个有损的过程，因为单独的边路径彼此挤压，但是如果您在索引期间必需使用图形 **token** 流，因为Lucene索引当前无法表示图形。 因此，最好仅在搜索时间应用图形分析器，因为它保留了完整的图形结构，并为近似度查询提供了正确的匹配。

有关此主题及其各种复杂性的更多信息，请阅读[**Lucene’s TokenStreams are actually graphs**](http://blog.mikemccandless.com/2012/04/lucenes-tokenstreams-are-actually.html)博客文章。

## Length Token Filter（长度词元过滤器）

**length**类型的词元过滤器，可以删除流中过长或过短的字词。

以下是可以为**length** 类型词元过滤器设置的设置：

| 设置    | 描述                          |
| ----- | --------------------------- |
| `min` | 最小数值. 默认 `0`.               |
| `max` | 最大数值.默认`Integer.MAX_VALUE`. |

## Lowercase Token Filter（Lowercase 词元过滤器）

**lowercase** 类型的词元过滤器，将词元文本规范化为小写。

**Lowercase Token Filter**通过**language**参数支持 **Greek（希腊语）**，**Irish （爱尔兰语）**&#x548C; **Turkish（土耳其）**&#x5C0F;写词元过滤器。 以下是自定义分词器中的使用示例

```
index :
    analysis :
        analyzer :
            myAnalyzer2 :
                type : custom
                tokenizer : myTokenizer1
                filter : [myTokenFilter1, myGreekLowerCaseFilter]
                char_filter : [my_html]
        tokenizer :
            myTokenizer1 :
                type : standard
                max_token_length : 900
        filter :
            myTokenFilter1 :
                type : stop
                stopwords : [stop1, stop2, stop3, stop4]
            myGreekLowerCaseFilter :
                type : lowercase
                language : greek
        char_filter :
              my_html :
                type : html_strip
                escaped_tags : [xxx, yyy]
                read_ahead : 1024
```

## Uppercase Token Filter（Uppercase词元过滤器）

**uppercase** 类型的词元过滤器，将词元文本规范化为大写。

## NGram Token Filter（NGram词元过滤器）

**nGram**类型的词元过滤器。

以下是可以为**nGram**类型词元过滤器设置的设置：

| 设置         | 描述       |
| ---------- | -------- |
| `min_gram` | 默认值 `1`. |
| `max_gram` | 默认值`2`.  |

## Edge NGram Token Filter（Edge NGram 词元过滤器）

**edgeNGram**类型的词元过滤器。

以下是可以为**edgeNGram**类型词元过滤器设置的设置：

| 设置         | 描述                              |
| ---------- | ------------------------------- |
| `min_gram` | 默认值 `1`.                        |
| `max_gram` | 默认值 `2`.                        |
| `side`     | 已弃用.`front`/ `back`.默认值`front`. |

## Porter Stem Token Filter（Porter Stem 词元过滤器）

**porter\_stem**类型的词元过滤器，根据波特干扰算法转换词元流。

请注意，**Porter Stem**词元过滤器的输入必须已经是小写，所以您需要使用[**Lower Case Token Filter**](http://www.apache.wiki/pages/viewpage.action?pageId=10027085) or [**Lower Case Tokenizer**](https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-lowercase-tokenizer.html) 在之前的分词器链上，以使其正常工作！例如，使用自定义分词器时，请确保过滤器列表中的 **lowercase** 过滤器位于**porter\_stem**过滤器之前

## Shingle Token Filter（Shingle 词元过滤器）

**shingle**类型的词元过滤器，用于从词元流中构建 **shingles**（**token n-grams**）。 换句话说，它创建词元的组合作为单个词元。 例如，句子 “**please divide this sentence into shingles**” ，可能会被划分为词组“**please divide**”，“**divide this**”，“**this sentence**”，“**sentence into**”和“**into shingles**”。

此过滤器通过插入 **filler tokens**（使用“\_”的词元）来处理游标自增 > 1。游标不从0开始。

以下是 **shingle**类型的词元过滤器的可选设置：

| 设置                               | 描述                                                                                                                                        |
| -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
| `max_shingle_size`               | 最大的**shingle**数量. 默认 `2`.                                                                                                                 |
| `min_shingle_size`               | 最小的**shingle**数量. 默认 `2`.                                                                                                                 |
| `output_unigrams`                | 如果为 `true`输出将会包含输入的**tokens (unigrams)**&#x4EE5;及**shingles**. 默认 `true`.                                                                 |
| `output_unigrams_if_no_shingles` | 如果 `output_unigrams` 为`false` ，如果没有可用的**shingles**输出将会包含输入的**tokens (unigrams)**.**提示**如果 `output_unigrams` 为**true**当前设置不生效. 默认 `false`. |
| `token_separator`                | 连接相邻的词元生成词组的字符串. 默认 `" "`.                                                                                                                |
| `filler_token`                   | 用于替换流中每个没有实际词元的位置的字符串。例如，当**stop**过滤器与`shingle`过滤器一起使用时，如果位置增量大于1. 默认 `"_"`                                                               |

## Stop Token Filter（Stop 词元过滤器）

**stop**类型的词元过滤器，用于从词元流中移除**stop words**。

以下是**stop**类型的词元过滤器的可选设置：

| `stopwords`       | 停止词列表. 默认 `_english_` 无效词.                                                                                          |
| ----------------- | ------------------------------------------------------------------------------------------------------------------- |
| `stopwords_path`  | 无效词配置文件路径（绝对或者相对路径）. 每个停止词自占一行 (换行分隔). 文件必须是**UTF-8**编码.                                                            |
| `ignore_case`     | 设置为 `true`所有词被转为小写. 默认 `false`.                                                                                     |
| `remove_trailing` | 设置为**false**，以便不忽略搜索的最后一个字词，如果它是无效词。 这对于完成建议者非常有用，因为像**green a**一样的查询可以扩展到**green apple**，即使你删除一般的无效词。 默认为**true**。 |

**stopwords**参数接受一个数组类型的无效词：

```
PUT /my_index
{
    "settings": {
        "analysis": {
            "filter": {
                "my_stop": {
                    "type":       "stop",
                    "stopwords": ["and", "is", "the"]
                }
            }
        }
    }
}
```

或预定义的语言特定列表：

```
PUT /my_index
{
    "settings": {
        "analysis": {
            "filter": {
                "my_stop": {
                    "type":       "stop",
                    "stopwords":  "_english_"
                }
            }
        }
    }
}
```

**lasticsearch**提供以下预定义语言列表：

`_arabic_`**,** `_armenian_`**,** `_basque_`**,** `_brazilian_`**,** `_bulgarian_`**,** `_catalan_`**,** `_czech_`**,** `_danish_`**,** `_dutch_`**,** `_english_`**,** `_finnish_`**,** `_french_`**,** `_galician_`**,** `_german_`**,** `_greek_`**,** `_hindi_`**,** `_hungarian_`**,**`_indonesian_`**,** `_irish_`**,** `_italian_`**,** `_latvian_`**,** `_norwegian_`**,** `_persian_`**,** `_portuguese_`**,** `_romanian_`**,** `_russian_`**,** `_sorani_`**,** `_spanish_`**,** `_swedish_`**,** `_thai_`**,** `_turkish_`**.**

空的无效词列表（禁用无效词）使用：`\_none_。`

## Word Delimiter Token Filter（Word Delimiter 词元过滤器）

```
命名为 word_delimiter，它将单词分解为子词，并对子词组进行可选的转换。 词被分为以下规则的子词：
```

* 拆分字内分隔符（默认情况下，所有非字母数字字符）。.
* "Wi-Fi" → "Wi", "Fi"
* 按大小写转换拆分: "PowerShot" → "Power", "Shot"
* 按字母数字转换拆分: "SD500" → "SD", "500"
* 每个子词的前导和尾随的词内分隔符都被忽略: "//hello---there,&#x20;

  *dude*

  " → "hello", "there", "dude"
* 每个子词都删除尾随的“s”: "O’Neil’s" → "O", "Neil"

参数包括：

**generate\_word\_parts**

**true** 导致生成单词部分："PowerShot" ⇒ "Power" "Shot"。默认 **true**

**generate\_number\_parts**

**true** 导致生成数字子词："500-42" ⇒ "500" "42"。默认 **true**

**catenate\_numbers**

**true** 导致单词最大程度的链接到一起："wi-fi" ⇒ "wifi"。默认 **false**

**catenate\_numbers**

**true** 导致数字最大程度的连接到一起："500-42" ⇒ "50042"。默认 **false**

**catenate\_all**

**true** 导致所有的子词可以连接："wi-fi-4000" ⇒ "wifi4000"。默认 **false**

**split\_on\_case\_change**

**true** 导致 "PowerShot" 作为两个词元（"Power-Shot" 作为两部分看待）。默认 **true**

**preserve\_original**

**true** 在子词中保留原始词： "500-42" ⇒ "500-42" "500" "42"。默认 **false**

**split\_on\_numerics**

**true** 导致 "j2se" 成为三个词元： "j" "2" "se"。默认 **true**

**stem\_english\_possessive**

**true** 导致每个子词中的 "'s" 都会被移除："O’Neil’s" ⇒ "O", "Neil"。默认 **true**

高级设置：

**protected\_words**

被分隔时的受保护词列表。 一个数组，或者也可以将**protected\_words\_path**设置为配置有保护字的文件（每行一个）。 如果存在，则自动解析为基于**config/**&#x4F4D;置的位置。

**type\_table**

例如，自定义类型映射表（使用**type\_table\_path**配置时）：

```
# Map the $, %, '.', and ',' characters to DIGIT
# This might be useful for financial data.
$ => DIGIT
% => DIGIT
. => DIGIT
\\u002C => DIGIT

# in some cases you might not want to split on ZWJ
# this also tests the case where we need a bigger byte[]
# see http://en.wikipedia.org/wiki/Zero-width_joiner
\\u200D => ALPHANUM
```

**提示：**

使用像 `standard` **tokenizer**的**tokenizer**可能会干扰**catenate\_ \***&#x548C;**preserve\_original**参数，因为原始字符串在分词期间可能已经丢失了标点符号。 相反，您可能需要使用 `whitespace`**tokenizer**。

## Stemmer Token Filter（Stemmer 词元过滤器）

一个过滤器，通过单个统一接口提供（几乎）所有可用的词干词元过滤器的访问，例如：

```
{
    "index" : {
        "analysis" : {
            "analyzer" : {
                "my_analyzer" : {
                    "tokenizer" : "standard",
                    "filter" : ["standard", "lowercase", "my_stemmer"]
                }
            },
            "filter" : {
                "my_stemmer" : {
                    "type" : "stemmer",
                    "name" : "light_german"
                }
            }
        }
    }
}
```

**language / name**参数用以下可用值控制词干（首选过滤器以粗体标记）：

| Arabic               | [`arabic`](http://lucene.apache.org/core/4_9_0/analyzers-common/org/apache/lucene/analysis/ar/ArabicStemmer.html)                                                                                                                                                                                                                                                                                                                                                                                                                       |
| -------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Armenian             | [`armenian`](http://snowball.tartarus.org/algorithms/armenian/stemmer.html)                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| Basque               | [`basque`](http://snowball.tartarus.org/algorithms/basque/stemmer.html)                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| Brazilian Portuguese | [`brazilian`](http://lucene.apache.org/core/4_9_0/analyzers-common/org/apache/lucene/analysis/br/BrazilianStemmer.html)                                                                                                                                                                                                                                                                                                                                                                                                                 |
| Bulgarian            | [`bulgarian`](http://members.unine.ch/jacques.savoy/Papers/BUIR.pdf)                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| Catalan              | [`catalan`](http://snowball.tartarus.org/algorithms/catalan/stemmer.html)                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| Czech                | [`czech`](http://portal.acm.org/citation.cfm?id=1598600)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| Danish               | [`danish`](http://snowball.tartarus.org/algorithms/danish/stemmer.html)                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| Dutch                | [`dutch`](http://snowball.tartarus.org/algorithms/dutch/stemmer.html), [`dutch_kp`](http://snowball.tartarus.org/algorithms/kraaij_pohlmann/stemmer.html)                                                                                                                                                                                                                                                                                                                                                                               |
| English              | [`english`](http://snowball.tartarus.org/algorithms/porter/stemmer.html), [`light_english`](http://ciir.cs.umass.edu/pubfiles/ir-35.pdf), [`minimal_english`](http://www.researchgate.net/publication/220433848_How_effective_is_suffixing), [`possessive_english`](http://lucene.apache.org/core/4_9_0/analyzers-common/org/apache/lucene/analysis/en/EnglishPossessiveFilter.html), [`porter2`](http://snowball.tartarus.org/algorithms/english/stemmer.html),[`lovins`](http://snowball.tartarus.org/algorithms/lovins/stemmer.html) |
| Finnish              | [`finnish`](http://snowball.tartarus.org/algorithms/finnish/stemmer.html), [`light_finnish`](http://clef.isti.cnr.it/2003/WN_web/22.pdf)                                                                                                                                                                                                                                                                                                                                                                                                |
| French               | [`french`](http://snowball.tartarus.org/algorithms/french/stemmer.html), [`light_french`](http://dl.acm.org/citation.cfm?id=1141523), [`minimal_french`](http://dl.acm.org/citation.cfm?id=318984)                                                                                                                                                                                                                                                                                                                                      |
| Galician             | [`galician`](http://bvg.udc.es/recursos_lingua/stemming.jsp), [`minimal_galician`](http://bvg.udc.es/recursos_lingua/stemming.jsp) (Plural step only)                                                                                                                                                                                                                                                                                                                                                                                   |
| German               | [`german`](http://snowball.tartarus.org/algorithms/german/stemmer.html), [`german2`](http://snowball.tartarus.org/algorithms/german2/stemmer.html), [`light_german`](http://dl.acm.org/citation.cfm?id=1141523), [`minimal_german`](http://members.unine.ch/jacques.savoy/clef/morpho.pdf)                                                                                                                                                                                                                                              |
| Greek                | [`greek`](http://sais.se/mthprize/2007/ntais2007.pdf)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| Hindi                | [`hindi`](http://computing.open.ac.uk/Sites/EACLSouthAsia/Papers/p6-Ramanathan.pdf)                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| Hungarian            | [`hungarian`](http://snowball.tartarus.org/algorithms/hungarian/stemmer.html), [`light_hungarian`](http://dl.acm.org/citation.cfm?id=1141523\&dl=ACM\&coll=DL\&CFID=179095584\&CFTOKEN=80067181)                                                                                                                                                                                                                                                                                                                                        |
| Indonesian           | [`indonesian`](http://www.illc.uva.nl/Publications/ResearchReports/MoL-2003-02.text.pdf)                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| Irish                | [`irish`](http://snowball.tartarus.org/otherapps/oregan/intro.html)                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| Italian              | [`italian`](http://snowball.tartarus.org/algorithms/italian/stemmer.html), [`light_italian`](http://www.ercim.eu/publication/ws-proceedings/CLEF2/savoy.pdf)                                                                                                                                                                                                                                                                                                                                                                            |
| Kurdish (Sorani)     | [`sorani`](http://lucene.apache.org/core/4_9_0/analyzers-common/org/apache/lucene/analysis/ckb/SoraniStemmer.html)                                                                                                                                                                                                                                                                                                                                                                                                                      |
| Latvian              | [`latvian`](http://lucene.apache.org/core/4_9_0/analyzers-common/org/apache/lucene/analysis/lv/LatvianStemmer.html)                                                                                                                                                                                                                                                                                                                                                                                                                     |
| Lithuanian           | [`lithuanian`](http://svn.apache.org/viewvc/lucene/dev/branches/lucene_solr_5_3/lucene/analysis/common/src/java/org/apache/lucene/analysis/lt/stem_ISO_8859_1.sbl?view=markup)                                                                                                                                                                                                                                                                                                                                                          |
| Norwegian (Bokmål)   | [`norwegian`](http://snowball.tartarus.org/algorithms/norwegian/stemmer.html), [`light_norwegian`](http://lucene.apache.org/core/4_9_0/analyzers-common/org/apache/lucene/analysis/no/NorwegianLightStemmer.html), [`minimal_norwegian`](http://lucene.apache.org/core/4_9_0/analyzers-common/org/apache/lucene/analysis/no/NorwegianMinimalStemmer.html)                                                                                                                                                                               |
| Norwegian (Nynorsk)  | [`light_nynorsk`](http://lucene.apache.org/core/4_9_0/analyzers-common/org/apache/lucene/analysis/no/NorwegianLightStemmer.html), [`minimal_nynorsk`](http://lucene.apache.org/core/4_9_0/analyzers-common/org/apache/lucene/analysis/no/NorwegianMinimalStemmer.html)                                                                                                                                                                                                                                                                  |
| Portuguese           | [`portuguese`](http://snowball.tartarus.org/algorithms/portuguese/stemmer.html), [`light_portuguese`](http://dl.acm.org/citation.cfm?id=1141523\&dl=ACM\&coll=DL\&CFID=179095584\&CFTOKEN=80067181), [`minimal_portuguese`](http://www.inf.ufrgs.br/~buriol/papers/Orengo_CLEF07.pdf), [`portuguese_rslp`](http://www.inf.ufrgs.br//~viviane/rslp/index.htm)                                                                                                                                                                            |
| Romanian             | [`romanian`](http://snowball.tartarus.org/algorithms/romanian/stemmer.html)                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| Russian              | [`russian`](http://snowball.tartarus.org/algorithms/russian/stemmer.html), [`light_russian`](http://doc.rero.ch/lm.php?url=1000%2C43%2C4%2C20091209094227-CA%2FDolamic_Ljiljana_-_Indexing_and_Searching_Strategies_for_the_Russian_20091209.pdf)                                                                                                                                                                                                                                                                                       |
| Spanish              | [`spanish`](http://snowball.tartarus.org/algorithms/spanish/stemmer.html), [`light_spanish`](http://www.ercim.eu/publication/ws-proceedings/CLEF2/savoy.pdf)                                                                                                                                                                                                                                                                                                                                                                            |
| Swedish              | [`swedish`](http://snowball.tartarus.org/algorithms/swedish/stemmer.html), [`light_swedish`](http://clef.isti.cnr.it/2003/WN_web/22.pdf)                                                                                                                                                                                                                                                                                                                                                                                                |
| Turkish              | [`turkish`](http://snowball.tartarus.org/algorithms/turkish/stemmer.html)                                                                                                                                                                                                                                                                                                                                                                                                                                                               |

## Stemmer Override Token Filter（Stemmer Override 词元过滤器）

通过应用自定义映射来覆盖词干算法，然后保护这些术语不被词干修改。 必须放置在任何词干过滤器之前。

规则通过`=>`分隔开

| 设置           | 描述                                                       |
| ------------ | -------------------------------------------------------- |
| `rules`      | 映射规则列表.                                                  |
| `rules_path` | 映射列表文件的路径 (`config目录的相对路径或者绝对路径`) to a list of mappings. |

示例：

```
index :
    analysis :
        analyzer :
            myAnalyzer :
                type : custom
                tokenizer : standard
                filter : [lowercase, custom_stems, porter_stem]
        filter:
            custom_stems:
                type: stemmer_override
                rules_path : analysis/custom_stems.txt
```

## Keyword Marker Token Filter（Keyword Marker 词元过滤器）

```
保护词语不被词干分析器修改。 必须放置在任何词干过滤器之前。
```

| 设置              | 描述                                  |
| --------------- | ----------------------------------- |
| `keywords`      | 关键词列表.                              |
| `keywords_path` | 关键词列表文件的路径 (`config目录的相对路径或者绝对路径`). |
| `ignore_case`   | 设置为 `true` 会把词转化为小写. 默认 `false`.    |

示例：

```
index :
    analysis :
        analyzer :
            myAnalyzer :
                type : custom
                tokenizer : standard
                filter : [lowercase, protwords, porter_stem]
        filter :
            protwords :
                type : keyword_marker
                keywords_path : analysis/protwords.txt
```

## Keyword Repeat Token Filter（Keyword Repeat 词元过滤器）

**keyword\_repeat**词元过滤器将每个传入两次的词元发送一次作为关键字，一次作为非关键字，以允许将术语的未设置版本与该术语的主题版本并排编入索引。

鉴于此过滤器的性质，未被后续监听器转换的每个词元将被索引两次。 因此，考虑添加`unique`过滤器，**only\_on\_same\_position**设置为**true**可以丢弃不必要的重复项。

示例如下：

```
index :
    analysis :
        analyzer :
            myAnalyzer :
                type : custom
                tokenizer : standard
                filter : [lowercase, keyword_repeat, porter_stem, unique_stem]
            unique_stem:
                type: unique
                only_on_same_position : true
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://xiaoxiami.gitbook.io/elasticsearch/ji-chu/33-analysisfen-679029/335token-filtersff08-ci-yu-guo-lv-qi-ff09.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
