Elasticsearch:计数分词中的 token

1,674 阅读2分钟

在我们针对 text 类型的字段进行分词时,分词器会把该字段分解为一个个的 token。如果你对分词器还不是很理解的话,请参考我之前的文章 “Elasticsearch: analyzer”。在分词时,有一个叫做 token_count 的类型。该类型是 token 的计数器,也就是说,我们可以使用它来了解在索引字段时在字符串中生成的 token 数量。

我们下面用一个比较简单的例子来进行展示。在我们的示例中,我们将索引一些书名,并且我们将过滤标题中只有 2 个 token 的书。

`

1.  PUT book_token_count_test
2.  {
3.    "mappings": {
4.      "properties": {
5.        "book_name": {
6.          "type": "text",
7.          "fields": {
8.            "size": {
9.              "type": "token_count",
10.              "analyzer": "standard"
11.            }
12.          }
13.        }
14.      }
15.    }
16.  }

`![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)

我们使用如下的命令来写入一下文档:



1.  POST book_token_count_test/_bulk
2.  {"index":{}}
3.  { "book_name": "Ulysses" }
4.  {"index":{}}
5.  { "book_name": "Don Quixote" }
6.  {"index":{}}
7.  { "book_name": "One Hundred Years of Solitude" }


我们使用如下的命令来搜索 token 数为 2 的文档:



1.  GET book_token_count_test/_search
2.  {
3.    "query": {
4.      "term": {
5.        "book_name.size": {
6.          "value": "2"
7.        }
8.      }
9.    }
10.  }


上面搜索的结果为:

`

1.  {
2.    "took": 273,
3.    "timed_out": false,
4.    "_shards": {
5.      "total": 1,
6.      "successful": 1,
7.      "skipped": 0,
8.      "failed": 0
9.    },
10.    "hits": {
11.      "total": {
12.        "value": 1,
13.        "relation": "eq"
14.      },
15.      "max_score": 1,
16.      "hits": [
17.        {
18.          "_index": "book_token_count_test",
19.          "_id": "cxczBoYB6OPboMnB7TQu",
20.          "_score": 1,
21.          "_source": {
22.            "book_name": "Don Quixote"
23.          }
24.        }
25.      ]
26.    }
27.  }

`![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)

我们可以使用 range 查询来检索 book_name 中包含 3 个以上 token 的文档,我们只会得到标题为 “One Hundred Years of Solitude” 的文档。



1.  GET book_token_count_test/_search
2.  {
3.    "query": {
4.      "range": {
5.        "book_name.size": {
6.          "gte": 3
7.        }
8.      }
9.    }
10.  }


上面搜索的结果为:

`

1.  {
2.    "took": 1,
3.    "timed_out": false,
4.    "_shards": {
5.      "total": 1,
6.      "successful": 1,
7.      "skipped": 0,
8.      "failed": 0
9.    },
10.    "hits": {
11.      "total": {
12.        "value": 1,
13.        "relation": "eq"
14.      },
15.      "max_score": 1,
16.      "hits": [
17.        {
18.          "_index": "book_token_count_test",
19.          "_id": "dBczBoYB6OPboMnB7TQu",
20.          "_score": 1,
21.          "_source": {
22.            "book_name": "One Hundred Years of Solitude"
23.          }
24.        }
25.      ]
26.    }
27.  }

`![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)

希望这个小小的建议能帮助到你的工作!