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

### Pattern Capture Token Filter(模式匹配词元过滤器)

#### 简述

`pattern_capture词元`过滤器与`pattern 分词器`不同，为正则表达式中的每个捕获组发出一个token。

模式不会锚定到字符串的开始和结尾，每个模式可以匹配多次，并且允许重复匹配。

> 小心病态正则表达式 模式捕获令牌过滤器使用
>
> [Java正则表达式](http://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html)。 一个严重的正则表达式可能会运行得非常慢，甚至会抛出一个StackOverflowError，并导致其运行的节点突然退出。 阅读更多[关于病态正则表达式和如何避免它们](http://www.regular-expressions.info/catastrophic.html)。

#### 示例-1

举例如下：

正则：

```
"(([a-z]+)(\d*))"
```

待匹配文字：

```
"abc123def456"
```

匹配结果：

```
[ abc123, abc, 123, def456, def, 456 ]
```

如果`preserve_original`设置为`true` （默认值），那么它也会发出原始令牌： `abc123def456` 。

这对于索引文本（如驼峰式代码）特别有用，例如`stripHTML` ，用户可以在其中搜索`"strip html"`或`"striphtml"` ：

```
PUT test
{
   "settings" : {
      "analysis" : {
         "filter" : {
            "code" : {
               "type" : "pattern_capture",
               "preserve_original" : true,
               "patterns" : [
                  "(\\p{Ll}+|\\p{Lu}\\p{Ll}+|\\p{Lu}+)",
                  "(\\d+)"
               ]
            }
         },
         "analyzer" : {
            "code" : {
               "tokenizer" : "pattern",
               "filter" : [ "code", "lowercase" ]
            }
         }
      }
   }
}
```

当处理如下文本内容时：

```
import static org.apache.commons.lang.StringEscapeUtils.escapeHtml
```

结果如下：

```
[ import, static, org, apache, commons, lang, stringescapeutils, string, escape, utils, escapehtml, escape, html ]
```

#### 示例-2

别一个例子就是分析邮箱时，如下所示：

```
PUT test
{
   "settings" : {
      "analysis" : {
         "filter" : {
            "email" : {
               "type" : "pattern_capture",
               "preserve_original" : true,
               "patterns" : [
                  "([^@]+)",
                  "(\\p{L}+)",
                  "(\\d+)",
                  "@(.+)"
               ]
            }
         },
         "analyzer" : {
            "email" : {
               "tokenizer" : "uax_url_email",
               "filter" : [ "email", "lowercase",  "unique" ]
            }
         }
      }
   }
}
```

当邮箱格式如下时：

```
john-smith_123@foo-bar.com
```

最终处理结果将为：

```
john-smith_123@foo-bar.com, john-smith_123,
john, smith, 123, foo-bar.com, foo, bar, com
```

需要多种模式以允许重复捕获，但也意味着模式不复杂和易于理解。

注意：所有token都以相同的位置处理，并且具有相同的字符偏移量，因此当与突出显示相结合时，**整个原始token将被突出显示，而不仅仅是匹配的子集**。

例如，查询上述电子邮件地址`"smith",`将会突出显示整个原始token：

```
<em>john-smith_123@foo-bar.com</em>
```

而非仅高亮smith:

```
john-<em>smith</em>_123@foo-bar.com
```

### Pattern Replace Token Filter（模式替换词元过滤器）

#### 简述

`pattern_replace`过滤器可以容易地处理基于正则表达式的字符串替换。使用`pattern`参数定义正则表达式，并且可以使用`replacement`参数（支持引用原始文本，如下所述）提供要替换字符串。

> 小心病态正则表达式 模式捕获令牌过滤器使用
>
> [Java正则表达式](http://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html)。 一个严重的正则表达式可能会运行得非常慢，甚至会抛出一个StackOverflowError，并导致其运行的节点突然退出。 阅读更多[关于病态正则表达式和如何避免它们](http://www.regular-expressions.info/catastrophic.html)。

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

#### 简述

`trim`过滤器将会`trim掉token`周围的空格。

### Limit Token Count Token Filter(限制词元数量过滤器)

#### 简述

限制每个文档和字段索引的token数。

#### 参数

| 设置                   | 描述                                                                |
| -------------------- | ----------------------------------------------------------------- |
| `max_token_count`    | 每个文档和字段应该索引的token的最大数量。默认值为`1`                                    |
| `consume_all_tokens` | 如果设置为true,尽管已经超过max\_token\_count设定的值，也会最大限度的处理所有的token。默认为false。 |

## 示例 <a href="#limittokencounttokenfilter-xian-zhi-ci-yuan-shu-liang-guo-lv-qi-shi-li" id="limittokencounttokenfilter-xian-zhi-ci-yuan-shu-liang-guo-lv-qi-shi-li"></a>

如下所示：

```
index :
    analysis :
        analyzer :
            myAnalyzer :
                type : custom
                tokenizer : standard
                filter : [lowercase, five_token_limit]
        filter :
            five_token_limit :
                type : limit
```

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

#### 简述

Hunspell过滤器是Hunspell的基础。Hunspell字典将从文件系统上的专用hunspell目录（ `<path.conf>/hunspell` ）中`<path.conf>/hunspell` 。预期每个字典都有自己的目录，以其关联的语言环境（语言）命名。这个字典目录预计会保存一个`*.aff`和一个或多个`*.dic`文件（所有这些文件将自动被读取）。例如，假设使用默认的hunspell位置，以下目录布局将定义`en_US`字典：

```
- conf
    |-- hunspell
    |    |-- en_US
    |    |    |-- en_US.dic
    |    |    |-- en_US.aff
```

#### 参数

每个字典都可以进行一个设置：

```
ignore_case  
    如果为true，字典匹配将不区分大小写（默认为false ）
```

这个设置可以在`elasticsearch.yml`使用全局`elasticsearch.yml`

* `indices.analysis.hunspell.dictionary.ignore_case`

或指定特定字典：

* `indices.analysis.hunspell.dictionary.en_US.ignore_case`

还可以在保存这些设置的`settings.yml`目录下添加`settings.yml`文件（这将覆盖在`elasticsearch.yml`定义的任何其他设置）。

可以通过配置分析设置来使用hunspell过滤器：

```
{
    "analysis" : {
        "analyzer" : {
            "en" : {
                "tokenizer" : "standard",
                "filter" : [ "lowercase", "en_US" ]
            }
        },
        "filter" : {
            "en_US" : {
                "type" : "hunspell",
                "locale" : "en_US",
                "dedup" : true
            }
        }
    }
}
```

hunspell过滤器接受四个选项：

```
locale
    此过滤器的区域设置。 如果这没有设置，则使用lang或者language来代替它们，因此必须设置其中一个。

dictionary
    字典的名称 您的hunspell字典的路径应通过indices.analysis.hunspell.dictionary.location 。

dedup
    如果需要返回单条结果，则需要将其设置为true 。 默认为true 。

longest_only
    如果只返回最长的结果，请将其设置为true 。 默认为false ：返回所有可能的结果。
```

> 与（基于算法的） snowball stemmers（雪球词干分析器）相反，这是基于词典查找的，因此词干的质量由词典的质量决定。

#### 加载字典

默认情况下，当节点启动时，将为该字典检查默认的Hunspell目录（ `config/hunspell/` ），并自动加载任何字典。

通过在配置文件`indices.analysis.hunspell.dictionary.lazy`设置为`true` ，可以将字典加载实际使用。

#### 参考

Hunspell是一个拼写检查器和形态分析器，专为具有丰富形态和复杂的字复合和字符编码的语言而设计。

1. 维基百科， [http://en.wikipedia.org/wiki/Hunspell](https://translate.googleusercontent.com/translate_c?depth=1\&hl=zh-CN\&rurl=translate.google.com\&sl=en\&sp=nmt4\&tl=zh-CN\&u=http://en.wikipedia.org/wiki/Hunspell\&usg=ALkJrhhTe4SNBi-yzE2Ium7lZbYNdA0rjA)
2. 源代码， [http://hunspell.sourceforge.net/](https://translate.googleusercontent.com/translate_c?depth=1\&hl=zh-CN\&rurl=translate.google.com\&sl=en\&sp=nmt4\&tl=zh-CN\&u=http://hunspell.sourceforge.net/\&usg=ALkJrhjW2G8qRbu0lZQh2LVWUBJYgNKtWQ)
3. 开放办公室Hunspell字典， [http://wiki.openoffice.org/wiki/Dictionaries](https://translate.googleusercontent.com/translate_c?depth=1\&hl=zh-CN\&rurl=translate.google.com\&sl=en\&sp=nmt4\&tl=zh-CN\&u=http://wiki.openoffice.org/wiki/Dictionaries\&usg=ALkJrhjol_nl3ZVfCZVXqDENOiy7iD3A8g)
4. Mozilla Hunspell字典， [https://addons.mozilla.org/en-US/firefox/language-tools/](https://translate.googleusercontent.com/translate_c?depth=1\&hl=zh-CN\&rurl=translate.google.com\&sl=en\&sp=nmt4\&tl=zh-CN\&u=https://addons.mozilla.org/en-US/firefox/language-tools/\&usg=ALkJrhjkouoWClkhvx3I7BTP9HzM9bIOtw)
5. Chromium Hunspell字典， [http://src.chromium.org/viewvc/chrome/trunk/deps/third\_party/hunspell\_dictionaries/](https://translate.googleusercontent.com/translate_c?depth=1\&hl=zh-CN\&rurl=translate.google.com\&sl=en\&sp=nmt4\&tl=zh-CN\&u=http://src.chromium.org/viewvc/chrome/trunk/deps/third_party/hunspell_dictionaries/\&usg=ALkJrhjpxkhrlh-puMLQPulnPxd5rDvdxw)

### Common Grams Token Filter(近义词词元过滤器)

#### 简述

此过滤器，用于为经常出现的术语生成二进制码。单项仍被索引。当我们不想完全忽略常用术语时，它可以用作“ [停止令牌过滤器”](https://www.elastic.co/guide/en/elasticsearch/reference/5.3/analysis-stop-tokenfilter.html)的替代方法。如"the quick brown is a fox",将被过滤成 "the", "the\_quick", "quick", "brown", "brown\_is", "is\_a", "a\_fox", "fox"。假设“the”，“is”和“a”是常用词。

当启用`query_mode`时，过滤器将删除常用单词和单个术语，后跟通用单词。应在搜索分析器中启用此参数。如，"the quick brown is a fox" 将被过滤成 "the\_quick", "quick", "brown\_is", "is\_a", "a\_fox", "fox"。

#### 参数

以下是常用设置：

| 设置                  | 描述                                                                |
| ------------------- | ----------------------------------------------------------------- |
| `common_words`      | 要使用的常用词列表。                                                        |
| `common_words_path` | 路径（相对于`config`位置，或绝对）到常用单词列表。每个单词应该在自己的“行”（用换行符分隔）。该文件必须是UTF-8编码。 |
| `ignore_case`       | 如果为真，通用单词匹配将不区分大小写（默认为`false` ）。                                  |
| `query_mode`        | 生成二进制，然后删除常用单词和单个术语，后跟一个通用单词（默认为`false` ）。                        |

注意， `common_words`或`common_words_path`字段是必需的。

#### 示例

如下所示：

```
index :
    analysis :
        analyzer :
            index_grams :
                tokenizer : whitespace
                filter : [common_grams]
            search_grams :
                tokenizer : whitespace
                filter : [common_grams_query]
        filter :
            common_grams :
                type : common_grams
                common_words: [a, an, the]
            common_grams_query :
                type : common_grams
                query_mode: true
                common_words: [a, an, the]
```

### Normalization Token Filter（标准化词元过滤器）

#### 简述

有几个词元过滤器可用于尝试规范某种语言的特殊字符。

| 阿拉伯          | [`arabic_normalization`](http://lucene.apache.org/core/4_9_0/analyzers-common/org/apache/lucene/analysis/ar/ArabicNormalizer.html)                                                                                                                                                                                         |
| ------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 德语           | [`german_normalization`](http://lucene.apache.org/core/4_9_0/analyzers-common/org/apache/lucene/analysis/de/GermanNormalizationFilter.html)                                                                                                                                                                                |
| 印地语          | [`hindi_normalization`](http://lucene.apache.org/core/4_9_0/analyzers-common/org/apache/lucene/analysis/hi/HindiNormalizer.html)                                                                                                                                                                                           |
| 印度           | [`indic_normalization`](http://lucene.apache.org/core/4_9_0/analyzers-common/org/apache/lucene/analysis/in/IndicNormalizer.html)                                                                                                                                                                                           |
| 库尔德语（Sorani） | [`sorani_normalization`](http://lucene.apache.org/core/4_9_0/analyzers-common/org/apache/lucene/analysis/ckb/SoraniNormalizer.html)                                                                                                                                                                                        |
| 波斯语          | [`persian_normalization`](http://lucene.apache.org/core/4_9_0/analyzers-common/org/apache/lucene/analysis/fa/PersianNormalizer.html)                                                                                                                                                                                       |
| 斯堪的纳维亚文      | [`scandinavian_normalization`](http://lucene.apache.org/core/4_9_0/analyzers-common/org/apache/lucene/analysis/miscellaneous/ScandinavianNormalizationFilter.html), [`scandinavian_folding`](http://lucene.apache.org/core/4_9_0/analyzers-common/org/apache/lucene/analysis/miscellaneous/ScandinavianFoldingFilter.html) |
| 塞尔维亚         | not-released-yet\[`serbian_normalization`],                                                                                                                                                                                                                                                                                |

### CJK Width Token Filter（CJK宽度过滤器）

#### 简述

`cjk_width`令牌过滤器归一化CJK宽度差异：

* 将全宽ASCII变体折叠成等效的基本拉丁语
* 将片假片变体的半角折叠成相当的假名

> 该令牌过滤器可以被视为NFKC / NFKD Unicode归一化的子集。有关完整的规范化支持，请参阅[`analysis-icu`插件](https://www.elastic.co/guide/en/elasticsearch/plugins/5.3/analysis-icu-normalization-charfilter.html)。

### CJK Bigram Token Filter（CJK Bigram词元过滤器）

#### 简述

`cjk_bigram`过滤器形成了由[`standard` tokenizer](https://www.elastic.co/guide/en/elasticsearch/reference/5.3/analysis-standard-tokenizer.html)或icu\_tokenizer生成的CJK术语中的`icu_tokenizer`（见[`analysis-icu`插件](https://www.elastic.co/guide/en/elasticsearch/plugins/5.3/analysis-icu-tokenizer.html) ）。

默认情况下，当一个CJK字符没有相邻字符形成一个二进制格式时，它以单格形式输出。如果您总是输出unigrams和bigrams，请将`output_unigrams`标志设置为`true` 。这可以用于组合的unigram +二进制格式。

在`han` ， `hiragana` ， `katakana`和`hangul`中为字符生成Bigram，但对于具有`ignored_scripts`参数的特定脚本，可以禁用bigrams。所有非CJK输入都通过未修改。

#### 示例

```
{
    "index" : {
        "analysis" : {
            "analyzer" : {
                "han_bigrams" : {
                    "tokenizer" : "standard",
                    "filter" : ["han_bigrams_filter"]
                }
            },
            "filter" : {
                "han_bigrams_filter" : {
                    "type" : "cjk_bigram",
                    "ignored_scripts": [
                        "hiragana",
                        "katakana",
                        "hangul"
                    ],
                    "output_unigrams" : true
                }
            }
        }
    }
}
```

### Delimited Payload Token Filter（Delimited Payload词元分析器）

#### 简述

`名称命为delimited_payload_filter` 。每当发现分隔符时，将标记分成标记和有效载荷。

#### 示例

默认情况下，“1 quick | 2 fox | 3”被分为具有有效负载`1`和`3`令牌， `quick`和`fox` 。

#### 参数

delimiter: 用于分割令牌的字符。 默认值为| 。

encoding: 有效载荷的类型。 int为整数， float为浮点数和字符的identity 。 默认为float 。

### Keep Words Token Filter(保留字过滤器)

#### 简述

`当词元过滤器中的type为keep时，表示`只保留具有预定义单词集中的文本的token。可以在设置中定义一组单词，或者从包含每行一个单词的文本文件加载。

#### 参数

| keep\_words       | 要保留的单词列表                    |
| ----------------- | --------------------------- |
| keep\_words\_path | 一个文字文件的路径                   |
| keep\_words\_case | 一个布尔值，表示是否小写单词（默认为`false` ） |

#### 示例

```
PUT /keep_words_example
{
    "settings" : {
        "analysis" : {
            "analyzer" : {
                "example_1" : {
                    "tokenizer" : "standard",
                    "filter" : ["standard", "lowercase", "words_till_three"]
                },
                "example_2" : {
                    "tokenizer" : "standard",
                    "filter" : ["standard", "lowercase", "words_in_file"]
                }
            },
            "filter" : {
                "words_till_three" : {
                    "type" : "keep",
                    "keep_words" : [ "one", "two", "three"]
                },
                "words_in_file" : {
                    "type" : "keep",
                    "keep_words_path" : "analysis/example_word_list.txt"
                }
            }
        }
    }
}
```

### Keep Types Token Filter（保留指定类型过滤器）

### 简述

当type为`keep_types时`，过滤器将只保留包含在预定义集合中的token。

### 参数

| types | 要保留的类型列表 |
| ----- | -------- |

### 示例

你可以这样设置：

```
PUT /keep_types_example
{
    "settings" : {
        "analysis" : {
            "analyzer" : {
                "my_analyzer" : {
                    "tokenizer" : "standard",
                    "filter" : ["standard", "lowercase", "extract_numbers"]
                }
            },
            "filter" : {
                "extract_numbers" : {
                    "type" : "keep_types",
                    "types" : [ "<NUM>" ]
                }
            }
        }
    }
}
```

并用下述文本进行测试：

```
POST /keep_types_example/_analyze
{
  "analyzer" : "my_analyzer",
  "text" : "this is just 1 a test"
}
```

返回结果：

```
{
  "tokens": [
    {
      "token": "1",
      "start_offset": 13,
      "end_offset": 14,
      "type": "<NUM>",
      "position": 3
    }
  ]
}
```

注意输出中只有`<NUM> token（只有数字1,其他文本都被忽略了`。

### Classic Token Filter(经典过滤器)

#### 简述

classic过滤器对由[classic tokenizer](https://www.elastic.co/guide/en/elasticsearch/reference/5.4/analysis-classic-tokenizer.html)生成的词元做可选的后处理。

这个过滤器从单词的结尾处删除了英文所有权，并且它从首字母缩略词中删除了点。

### Apostrophe Token Filter(撇号/单引号过滤器)

#### 简述

`apostrophe`过滤器将过滤撇号后的所有字符，包括撇号本身。

### Decimal Digit Token Filter(十进制数字过滤器)

#### 简述

`decimal_digit`过滤器将unicode数字转化为`0-9。`

### Fingerprint Token Filter(指纹过滤器)

#### 简述

`fingerprint`过滤器发出单个token，该token对于指纹身份的文本和/或提供可以被聚类的token是有用的。它通过排序token，重复数据删除，然后将它们连接回单个token来实现。

#### 示例

如文本：\["the", "quick", "quick", "brown", "fox", "was", "very", "brown"]，将会被转化为单个token： "brown fox quick the very was"，注意token是按字母顺序排列的，并且只有一个`"quick"` 。

#### 参数

| 设置                | 描述         |
| ----------------- | ---------- |
| `separator`       | 默认为空格。     |
| `max_output_size` | 默认为`255` 。 |

#### 最大token大小

因为一个字段可能有许多独特的token，所以重要的是设置一个阈值，使得字段不会变得太大。`max_output_size`设置控制此行为。如果连接的指纹增长大于`max_output_size` ，则过滤器将退出并且不会发出token（例如，该字段将为空）。

### Minhash Token Filter(Minhash过滤器)

#### 简述

min\_hash 过滤器将token流中每个token一一哈希，并将生成的哈希值分成buckets，以保持每bucket最低值的散列值。然后将这些哈希值作为token(词元)返回。

#### 参数

| 设置              | 描述                                                                                                     |
| --------------- | ------------------------------------------------------------------------------------------------------ |
| `hash_count`    | 散列token流的散列数。默认为`1` 。                                                                                  |
| `bucket_count`  | 将minhash分成的bucket数。默认为`512` 。                                                                          |
| `hash_set_size` | 每bucket要保留的最小数量。默认为`1` 。                                                                               |
| `with_rotation` | 是否将空bucket中的第一个非空bucket的值填充到其循环右边。仅当hash\_set\_size等于1时才生效。如果bucket\_count大于1，则默认为`true` ，否则为`false` 。 |


---

# 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/335bu-chong-2-token-filters-ff08-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.
