# 3.3.5.补充1:Token Filters（词语过滤器）

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

**kstem**词元过滤器是用于英语的高性能过滤器。 所有词必须已经小写（使用`lowercase`过滤器）才能使此过滤器正常工作。

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

一个过滤器，使用 **Snowball-generated**的分词器来分词。`language`参数使用以下可用值控制分词器:`Armenian`**,** `Basque`**,** `Catalan`**,** `Danish`**,** `Dutch`**,** `English`**,** `Finnish`**,** `French`**,** `German`**,** `German2`**,** `Hungarian`**,** `Italian`**,** `Kp`**,** `Lithuanian`**,** `Lovins`**,** `Norwegian`**,** `Porter`**,** `Portuguese`**,** `Romanian`**,** `Russian`**,** `Spanish`**,** `Swedish`**,** `Turkish`**.**

例如：

```
PUT /my_index
{
    "settings": {
        "analysis" : {
            "analyzer" : {
                "my_analyzer" : {
                    "tokenizer" : "standard",
                    "filter" : ["standard", "lowercase", "my_snow"]
                }
            },
            "filter" : {
                "my_snow" : {
                    "type" : "snowball",
                    "language" : "Lovins"
                }
            }
        }
    }
}
```

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

**phonetic （语音）**&#x8BCD;元过滤器作为[`analysis-phonetic`](https://www.elastic.co/guide/en/elasticsearch/plugins/5.4/analysis-phonetic.html) 插件提供。

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

`synonym`**（同义词）**&#x8BCD;元过滤器允许在分析过程中轻松处理同义词。 同义词使用配置文件配置。示例如下：

```
PUT /test_index
{
    "settings": {
        "index" : {
            "analysis" : {
                "analyzer" : {
                    "synonym" : {
                        "tokenizer" : "whitespace",
                        "filter" : ["synonym"]
                    }
                },
                "filter" : {
                    "synonym" : {
                        "type" : "synonym",
                        "synonyms_path" : "analysis/synonym.txt"
                    }
                }
            }
        }
    }
}
```

以上配置一个 `synonym`（同义词）过滤器，其中包含一个路径**analysis/synonym.txt**（相对于 **config**的位置）。 然后使用过滤器配置`synonym`同义词分析器。 其他设置有：**ignore\_case**（默认为**false**），和`expand`（默认为**true**）。

**tokenizer**参数控制将用于标记同义词的分词器，并且默认为`whitespace` 分词器。

支持两种同义词格式：**Solr，WordNet**。

### **Solr synonyms** <a href="#synonymtokenfiltersynonym-ci-yuan-guo-lv-qi-solrsynonyms" id="synonymtokenfiltersynonym-ci-yuan-guo-lv-qi-solrsynonyms"></a>

以下是文件的示例格式：

```
# Blank lines and lines starting with pound are comments.

# Explicit mappings match any token sequence on the LHS of "=>"
# and replace with all alternatives on the RHS.  These types of mappings
# ignore the expand parameter in the schema.
# Examples:
i-pod, i pod => ipod,
sea biscuit, sea biscit => seabiscuit

# Equivalent synonyms may be separated with commas and give
# no explicit mapping.  In this case the mapping behavior will
# be taken from the expand parameter in the schema.  This allows
# the same synonym file to be used in different synonym handling strategies.
# Examples:
ipod, i-pod, i pod
foozball , foosball
universe , cosmos
lol, laughing out loud

# If expand==true, "ipod, i-pod, i pod" is equivalent
# to the explicit mapping:
ipod, i-pod, i pod => ipod, i-pod, i pod
# If expand==false, "ipod, i-pod, i pod" is equivalent
# to the explicit mapping:
ipod, i-pod, i pod => ipod

# Multiple synonym mapping entries are merged.
foo => foo bar
foo => baz
# is equivalent to
foo => foo bar, baz
```

您也可以在配置文件中直接给过滤器定义同义词（请注意使用**synonyms**而不是**synonyms\_path**）：

```
PUT /test_index
{
    "settings": {
        "index" : {
            "analysis" : {
                "filter" : {
                    "synonym" : {
                        "type" : "synonym",
                        "synonyms" : [
                            "i-pod, i pod => ipod",
                            "universe, cosmos"
                        ]
                    }
                }
            }
        }
    }
}
```

但是，建议使用**synonyms\_path** 在文件中定义大型同义词集，因为内联指定会不必要地增加群集大小。

### **WordNet synonyms** <a href="#synonymtokenfiltersynonym-ci-yuan-guo-lv-qi-wordnetsynonyms" id="synonymtokenfiltersynonym-ci-yuan-guo-lv-qi-wordnetsynonyms"></a>

基于 WordNet 格式的 同义词 可以如下使用格式声明：

```
 PUT /test_index
{
    "settings": {
        "index" : {
            "analysis" : {
                "filter" : {
                    "synonym" : {
                        "type" : "synonym",
                        "format" : "wordnet",
                        "synonyms" : [
                            "s(100000001,1,'abstain',v,1,0).",
                            "s(100000001,2,'refrain',v,1,0).",
                            "s(100000001,3,'desist',v,1,0)."
                        ]
                    }
                }
            }
        }
    }
}
```

同时支持使用`synonyms_path`在文本中定义 **WordNet synonyms**。

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

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

**synonym\_graph**词元过滤器允许在分析过程中轻松处理同义词，包括多字同义词。

为了正确处理多字同义词，该词元过滤器在处理过程中创建 “**graph token stream**”。 有关此主题及其各种复杂性的更多信息，请阅读[**Lucene’s TokenStreams are actually graphs**](http://blog.mikemccandless.com/2012/04/lucenes-tokenstreams-are-actually.html) 博客文章。

**提示：**&#x8BE5;词元过滤器被设计为仅用作搜索分析器的一部分。 如果要在索引期间应用同义词，请使用标准[**synonym token filter**](http://www.apache.wiki/pages/viewpage.action?pageId=10028859)。

同义词使用配置文件配置。 这是一个例子：

```
PUT /test_index
{
    "settings": {
        "index" : {
            "analysis" : {
                "analyzer" : {
                    "search_synonyms" : {
                        "tokenizer" : "whitespace",
                        "filter" : ["graph_synonyms"]
                    }
                },
                "filter" : {
                    "graph_synonyms" : {
                        "type" : "synonym_graph",
                        "synonyms_path" : "analysis/synonym.txt"
                    }
                }
            }
        }
    }
}
```

以上配置一个 `search_synonyms`（同义词）过滤器，其中包含一个路径 **analysis/synonym.txt**（相对于 **config** 的位置）。 然后使用过滤器配置 `search_synonyms`同义词分析器。 其他设置有：**ignore\_case**（默认为 **false**），和 `expand`（默认为 **true**）。

**tokenizer** 参数控制将用于标记同义词的分词器，并且默认为 `whitespace` 分词器。

支持两种同义词格式：**Solr，WordNet**。

### **Solr synonyms** <a href="#synonymgraphtokenfiltersynonymgraph-ci-yuan-guo-lv-qi-solrsynonyms" id="synonymgraphtokenfiltersynonymgraph-ci-yuan-guo-lv-qi-solrsynonyms"></a>

以下是文件的示例格式：

```
# Blank lines and lines starting with pound are comments.

# Explicit mappings match any token sequence on the LHS of "=>"
# and replace with all alternatives on the RHS.  These types of mappings
# ignore the expand parameter in the schema.
# Examples:
i-pod, i pod => ipod,
sea biscuit, sea biscit => seabiscuit

# Equivalent synonyms may be separated with commas and give
# no explicit mapping.  In this case the mapping behavior will
# be taken from the expand parameter in the schema.  This allows
# the same synonym file to be used in different synonym handling strategies.
# Examples:
ipod, i-pod, i pod
foozball , foosball
universe , cosmos
lol, laughing out loud

# If expand==true, "ipod, i-pod, i pod" is equivalent
# to the explicit mapping:
ipod, i-pod, i pod => ipod, i-pod, i pod
# If expand==false, "ipod, i-pod, i pod" is equivalent
# to the explicit mapping:
ipod, i-pod, i pod => ipod

# Multiple synonym mapping entries are merged.
foo => foo bar
foo => baz
# is equivalent to
foo => foo bar, baz
```

您也可以在配置文件中直接给过滤器定义同义词（请注意使用 **synonyms**而不是 **synonyms\_path**）：

```
PUT /test_index
{
    "settings": {
        "index" : {
            "analysis" : {
                "filter" : {
                    "synonym" : {
                        "type" : "synonym_graph",
                        "synonyms" : [
                            "lol, laughing out loud",
                            "universe, cosmos"
                        ]
                    }
                }
            }
        }
    }
}
```

但是，建议使用 **synonyms\_path** 在文件中定义大型同义词集，因为内联指定会不必要地增加群集大小。

### **WordNet synonyms** <a href="#synonymgraphtokenfiltersynonymgraph-ci-yuan-guo-lv-qi-wordnetsynonyms" id="synonymgraphtokenfiltersynonymgraph-ci-yuan-guo-lv-qi-wordnetsynonyms"></a>

基于 WordNet 格式的 同义词 可以如下使用格式声明：

```
PUT /test_index
{
    "settings": {
        "index" : {
            "analysis" : {
                "filter" : {
                    "synonym" : {
                        "type" : "synonym_graph",
                        "format" : "wordnet",
                        "synonyms" : [
                            "s(100000001,1,'abstain',v,1,0).",
                            "s(100000001,2,'refrain',v,1,0).",
                            "s(100000001,3,'desist',v,1,0)."
                        ]
                    }
                }
            }
        }
    }
}
```

同时支持使用 `synonyms_path`在文本中定义 **WordNet synonyms**。

## Compound Word Token Filter（复合词过滤器）

### 简述

`hyphenation_decompounder`和`dictionary_decompounder`过滤器可以将许多德语中的复合词进行拆分。

两个过滤器都需要单词字典，可以按如下方式提供：

| `word_list`      | 或一系列字，在令牌过滤器配置中内联指定                     |
| ---------------- | --------------------------------------- |
| `word_list_path` | UTF-8编码文件的路径（绝对或相对于`config`目录），每行包含一个字。 |

### Hyphenation decompounder（连词分解）

`hyphenation_decompounder`使用连字符语法来查找潜在的字词，然后对单词字典进行检查。输出的token质量与您使用的语法文件的质量直接相关。对于像德语这样的语言是非常适用的。

基于XML的连字符语法文件可以在“ [对象格式化对象](http://offo.sourceforge.net/#FOP+XML+Hyphenation+Patterns) （OFFO）Sourceforge”项目中找到。目前仅支持FOP v1.2兼容连字符文件。您可以直接下载[offo-hyphenation\_v1.2.zip](https://sourceforge.net/projects/offo/files/offo-hyphenation/1.2/offo-hyphenation_v1.2.zip/downloadALkJrhh1HOK03GnbuWiuoThBDDDion7pCg)并查看`offo-hyphenation/hyph/`目录。想了解更多可以去查看Apache FOP项目。

### Dictionary decompounder（字典分解）

`dictionary_decompounder`使用强力方法与仅字典字典结合使用复合词中的子词。它比连字符分解器慢得多，但可以作为检验字典质量的第一步。

### Compound token filter parameters（复合词元过滤器参数）

以下参数可用于配置复合词元过滤器：

| `type`                      | 任何一个`dictionary_decompounder`或者是`hyphenation_decompounder` 。 |
| --------------------------- | ------------------------------------------------------------ |
| `word_list`                 | 包含用于单词字典的单词列表的数组。                                            |
| `word_list_path`            | 单词字典的路径（绝对或相对于`config`目录）。                                   |
| `hyphenation_patterns_path` | FOP XML连字符模式文件的路径（绝对或相对于`config`目录）。（当连词分解时需要配置）             |
| `min_word_size`             | 最小字大小。默认为5。                                                  |
| `min_subword_size`          | 最小子字大小。默认为2。                                                 |
| `max_subword_size`          | 最大字大小。默认为15。                                                 |
| `only_longest_match`        | 是否只包括最长的匹配子字。默认为`false`                                      |

如下例所示：

```
index :
    analysis :
        analyzer :
            myAnalyzer2 :
                type : custom
                tokenizer : standard
                filter : [myTokenFilter1, myTokenFilter2]
        filter :
            myTokenFilter1 :
                type : dictionary_decompounder
                word_list: [one, two, three]
            myTokenFilter2 :
                type : hyphenation_decompounder
                word_list_path: path/to/words.txt
                hyphenation_patterns_path: path/to/fop.xml
                max_subword_size : 22
```

## Reverse Token Filter(反向词元过滤器)

### 简述

`reverse`类型的词元过滤器，简单地反转每个词元。

## Elision Token Filter(Elision词元过滤器)

### 简述

此过滤器可以过滤省略元音。如，"l’avion" (the plane) 将会被过滤成 "avion" (plane)。

支持articles参数，其值为一组stop words（停止词，没有实际含义可忽略的词）。如下例所示：

```
"index" : {
    "analysis" : {
        "analyzer" : {
            "default" : {
                "tokenizer" : "standard",
                "filter" : ["standard", "elision"]
            }
        },
        "filter" : {
            "elision" : {
                "type" : "elision",
                "articles" : ["l", "m", "t", "qu", "n", "s", "j"]
            }
        }
    }
}
```

## Truncate Token Filter（截断词元过滤器）

### 简述

`truncate词元`过滤器可用于将token截短为特定长度。

它接受一个`length`参数，控制要截断的字符数，默认为`10` 。

## Unique Token Filter（唯一词元过滤器）

### 简述

`唯一词元`过滤器用于在分析期间仅索引唯一的token。默认情况下，它应用于所有词元流。

如果`only_on_same_position`设置为`true` ，则只会删除相同位置上的重复token。
