elasticsearch Mapping 设置

elasticsearch 中的 Mapping 类似关系型数据库的schema,也是可以自己进行类型上的设置的。合理的设置可以减小查询速度,和占用空间,也可以保护一些敏感字段不被检索到

Mapping

  • Mapping 类似数据库的 schema 的定义

    • 定义索引中的字段名称
    • 字段的数据类型
    • 字段,倒排索引的相关配置
  • Mapping 会把JSON文档映射成Lucenes所需要的扁平格式

  • 一个Mapping属于一个索引的Type

    • 每个文档都属于一个Type
    • 一个Type有一个Mapping定义
    • 7.0开始,不需要在Mapping定义中指定type信息

    字段的数据类型

    • 简单类型
      • text/keyword
      • Date
      • integer/floating
      • boolean
      • IPV4&IPV6
    • 复杂类型-对象和嵌套对象
      • 对象类型/嵌套类型
    • 特殊类型
      • geo_point & geo_shape /percolator

Dynamic Mapping

 * 在写文档的时候,如果索引不存在,会自动创建索引
 * Dynamic Mapping 的机制,使得我们无需手动定义Mappings。Elasticsearch会自动根据文档信息,推算字段类型
 * 但是有时候会推算不对,比如地理位置
 * 当类型如果设置不对时,会导致一些功能无法正常使用
 

类型自动识别

json类型 elasticsearch类型
字符串 * 匹配日期格式,设置成Date
* 配置数字设置为 float 或者 log 默认关闭
* 设置text,并且增加keyword子字段
布尔值 boolean
浮点数 faloat
整数 long
对象 object
数组 由第一个非空数值的类型决定
空值 忽略

能否更改Mapping字段类型

  • 两种情况
    • Dynamic 设置为true时,一旦有新增字段的文档写入,Mapping也同时被更新
    • Dynamic 设置为false,Mapping不会被更新,新增字段的数据无法被索引,但是信息会出现在_source中
    • Dynamic 设置成为strict,文档写入失败
  • 对已有字段,一旦已经有数据写入,就不会再自持修改自定义
    • Lucene实现的倒排索引,一旦完成就不允许修改
  • 如果希望改变字段类型,必须Reindex API,重建索引
1
2
3
4
5
6
7
8
//设置
PUT users/_mapping
{
"dynamic":false
}

//查看
GET users/_mapping

显示定义Mapping

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
 PUT users_text
{
"mappings": {
"properties": {
"name":{
"type": "text"
},
"age":{
"type": "integer"
},
"tel":{
"type": "text",
"index": false
}
}
}
}

ps:建议建立临时index写入样本创建,避免出错。

禁止查询字段

  • "index": false 不会被索引

index options

  • 四种不同级别的 index options 配置,可以控制倒排索引记录内容

    • docs-记录 doc id
    • freqs-记录 doc id 和 trem frequencies
    • positions-记录 doc id / trem frequencies/term position
    • offsets- doc id / trem frequencies/term position/character offects
  • text 类型默认 positions,其他默认doc id

  • 记录越多,越栈空间

null_value

  • 写入时也需要写入null
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
PUT users_text2
{
"mappings": {
"properties": {
"name":{
"type": "text"
},
"age":{
"type": "integer"
},
"tel":{
"type": "keyword",
"null_value": "NULL"
}
}
}
}

写入

1
2
3
4
5
6
PUT users_text2/_create/2
{
"name":"zjj",
"age":25,
"tel":null
}

copt_to设置

  • _all 在7中被 cpoy_to代替
  • 满足一些特定的搜索需求
  • copy_to 讲字段的数组拷贝到目标字段,实现类似_all作用
  • copy_to的目标字段不出现在_source中
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
PUT users_3
{
"mappings": {
"properties": {
"name":{
"type": "text",
"copy_to": "userinfo"
},
"age":{
"type": "text",
"copy_to": "userinfo"
}
}
}
}

数组

  • 自己理解这个数组只是逻辑上的加上json
1
2
3
4
5
PUT users_3/_create/2
{
"name":"zjj",
"age":["24","25"]
}

  • 版权声明: 本博客所有文章除特别声明外,著作权归作者所有。转载请注明出处!

请我喝杯咖啡吧~