[关闭]
@runzhliu 2018-01-25T02:06:48.000000Z 字数 1015 阅读 1065

Elasticsearch keyword 和 text 类型

elasticsearch keyword text


参考资料
Strings are dead, long live strings!

关于 Elasticsearch 有很多中文博客多有介绍 keywordtext 的区别,基本都是源自于官方文档,笔者在这里把官方社区中的博客贴出来,并作简单翻译,供其他人参考。

1 Text vs. keyword

在 Elasticsearch 5.0 发布后,string 类型被正式去除。原因在于该类型总是会制造很多混乱,因为在 Elasticsearch 中有两种不同的方式来检索字符,既可以搜索全字符,又可以搜索词项 token。而一般前者的 mapping 是需要加上 not_analyzed,而后者是需要 analyzed。这一特性保留在了 Elasticsearch 6.1 当中。

为了避免这些误会,string 类型被分为 textkeyword 两种类型,前者作为全文检索,后者是关键词检索的类型。

2 New defaults

而默认的字符串动态 mapping 也做了修改,字符串会被动态的以 textkeyword 两种类型被索引。

如果需要索引以下字段:

  1. {
  2. "foo": "bar"
  3. }

动态 mapping 的效果为:

  1. {
  2. "foo": {
  3. "type" "text",
  4. "fields": {
  5. "keyword": {
  6. "type": "keyword",
  7. "ignore_above": 256
  8. }
  9. }
  10. }
  11. }

当然你可以采用显示的方式来定义 mapping 以避免同时被索引成两种类型。

3 How to migrate

下面展示的是如何索引文档的字符型字段成需要的类型。

针对以前需要 analyzedstring 字段,可以简单的使用 textindex: true 来设定。

  1. {
  2. "foo": {
  3. "type" "string",
  4. "index": "analyzed"
  5. }
  6. }
  1. {
  2. "foo": {
  3. "type" "text",
  4. "index": true
  5. }
  6. }

针对以前需要 not_analyzedstring 字段,可以简单使用 keywordindex: true 来设定。

  1. {
  2. "foo": {
  3. "type" "string",
  4. "index": "not_analyzed"
  5. }
  6. }
  1. {
  2. "foo": {
  3. "type" "keyword",
  4. "index": true
  5. }
  6. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注