es 关于text和keyword搜索区别

ElasticSearch 5.0以后,string类型有重大变更,移除了string类型,string字段被拆分成两种新的数据类型: text用于全文搜索的,而keyword用于关键词搜索。

ElasticSearch字符串将默认被同时映射成text和keyword类型,将会自动创建下面的动态映射。

通过 GET /dist_wechat_14_38/_mapping/field/weixin_number 命令查看 weixin_number 字段数据类型,可以看到 mapping 下除了 text 还有 keyword。两者有什么区别呢? 

{
  "dist_wechat_v4_14_38_20220620" : {
    "mappings" : {
      "weixin" : {
        "weixin_number" : {
          "full_name" : "weixin_number",
          "mapping" : {
            "weixin_number" : {
              "type" : "text",
              "fields" : {
                "keyword" : {
                  "type" : "keyword",
                  "ignore_above" : 256
                }
              }
            }
          }
        }
      }
    }
  }
}

text:

会分词,然后进行索引

支持模糊、精确查询

不支持聚合

分词器默认standard ,对于中文来说就是按字分词

支持fields属性,可以在fields中添加keyword子类型,以实现精确检索

keyword:

不进行分词,直接索引

支持模糊、精确查询

支持聚合

支持按字数建立索引,以便节约索引空间

看下text分词规律。

1、纯小写字符串

GET /dist_wechat_14_38/_analyze
{
  "field": "weixin_number",
  "text": "vicky1176320626"
}

{
  "tokens" : [
    {
      "token" : "vicky1176320626",
      "start_offset" : 0,
      "end_offset" : 15,
      "type" : "<ALPHANUM>",
      "position" : 0
    }
  ]
}

2、包含大写字母字符串会全部转换为小写。

GET /dist_wechat_14_38/_analyze
{
  "field": "weixin_number",
  "text": "XP3412"
}

{
  "tokens" : [
    {
      "token" : "xp3412",
      "start_offset" : 0,
      "end_offset" : 6,
      "type" : "<ALPHANUM>",
      "position" : 0
    }
  ]
}

3、包含特殊符号,如空格、-,则会分词为多个字符串。

GET /dist_wechat_14_38/_analyze
{
  "field": "weixin_number",
  "text": "AAAA-95533"
}

{
  "tokens" : [
    {
      "token" : "aaaa",
      "start_offset" : 0,
      "end_offset" : 4,
      "type" : "<ALPHANUM>",
      "position" : 0
    },
    {
      "token" : "95533",
      "start_offset" : 5,
      "end_offset" : 10,
      "type" : "<NUM>",
      "position" : 1
    }
  ]
}

这也是某些情况下,term 查询后查询不到数据的原因。解决方案也很简单,使用 keyword 精确查询即可。

 

posted @ 2022-08-11 16:26  所见即我  阅读(4717)  评论(0编辑  收藏  举报