_mapping 映射

GET /megacorp/_mapping/employee

获取megacorp索引中的employee类型进行mapping,模式定义,当我们索引一个包含新域的文档时,Elasticsearch会使用动态映射,通过JSON中基本数据类型,尝试猜测域类型

ES中数据类型

在最新版本中,Filed datatypes ​​官网链接​​​ 简单的类型有 text、keyword、date、long、double、boolean和ip
复杂类型有:object和nested
较特殊的类型:geo_point,geo_shape,和completion

这里我主要理解对于String域字段的区分
在Elasticsearch中,正常添加数据,ES会自动识别所添加数据的类型,并为它分配类型,并为每个特殊类型分别建索引,以用来进行之后的搜索

而作为全文搜索引擎,ES将String域的字段可以分为准确数据类型,和全文文本类型
准确数据类型: keyword,直接被存储为了二进制,检索时我们直接匹配,不匹配就返回false
全文文本类型: text,这个的检索不是直接给出是否匹配,而是检索出相似度,并按照相似度由高到低返回结果

ES做到计算相似度的?

ES对于text类型的数据操作步骤:

  1. 将字段标记化,例如去除多余的HTML的标志符,将&转化为and
  2. 标准化,分词,将每个词都分开,一个个的terms,并将每个词都转化为其根词汇,例如复数类型都变成原始类型,大写的都以变成小写,也可以添加断词器,去除一些无用的连接词,如and,or等
  3. 然后对要检索的内容作相同的处理,然后进行匹配,计算相似度

分析器有很多种,但是一般情况standard就足够使用了

一个测试分析器的好办法:

GET /_analyze
{
  "text" : "Text is Yours",
  "analyzer" : "standard"
}

返回的是分词结果,注意观察txt、Yours的变化

{
  "tokens": [
    {
      "token": "text",
      "start_offset": 0,
      "end_offset": 4,
      "type": "<ALPHANUM>",
      "position": 0
    },
    {
      "token": "is",
      "start_offset": 5,
      "end_offset": 7,
      "type": "<ALPHANUM>",
      "position": 1
    },
    {
      "token": "yours",
      "start_offset": 8,
      "end_offset": 13,
      "type": "<ALPHANUM>",
      "position": 2
    }
  ]
}

自己定义字段是否为准确字段类型

添加gb索引,并规定其中属性类型

PUT /gb 
{
  "mappings": {
    "tweet" : {
      "properties" : {
        "tweet" : {
          "type" :    "text",
          "analyzer": "english"
        },
        "date" : {
          "type" :   "date"
        },
        "name" : {
          "type" :   "text"
        },
        "user_id" : {
          "type" :   "long"
        } 
      }
    }
  }
}

添加tweet1字段,并且为准确类型字段,完全匹配搜索

PUT gb/_mapping/tweet
{
  "properties" : {
    "tweet1" : {
      "type" : "keyword"
    }
  }
}