Dynamic Mapping
1.Dynamic Mapping的概念
Dynamic Mapping,顾名思义,就是指Elasticsearch能够动态的创建Mapping结构,不需要手动的设置Mapping文件。下面是官方文档中的描述:
One of the most important features of Elasticsearch is that it tries to get out of your way and let you start exploring your data as quickly as possible. To index a document, you don’t have to first create an index, define a mapping type, and define your fields — you can just index a document and the index, type, and fields will spring to life automatically
2.Dynamic Mapping的特点
- 在写入文档的时候,如果索引不存在,会自动创建索引
- Dynamic Mapping的机制,使得我们无需手动定义Mappings,Elasticsearch会自动根据文档信息,推算出字段的类型
- 某些情况下,Elasticsearch会推断错误,比如地理位置信息
- 当类型如果设置不正确时,会导致一些功能无法使用,例如Range。
3.Dynamic Mapping的字段类型自动识别对照
JSON类型 | Elasticsearch类型 |
---|---|
字符串 | 匹配日期格式,设置为Date 匹配数字设置为float或者long,该选项默认关闭 设置为Text,并且增加keyword子字段 |
布尔值 | boolean |
浮点数 | float |
整数 | long |
对象 | Object |
数组 | 由第一个非空数值的类型所决定 |
空值 | 忽略 |
4.Dynamic Mapping的三种设置
Dynamic Mapping共有三种设置,包括true、false、strict,默认是true。
- Dynamic 设置为true时,一旦有新增字段的文档写入,Mapping也同时被更新,该字段也能作为索引字段进行查询;
- Dynamic 设置为false时,Mapping不会被更新,同时该字段也不能作为索引字段进行查询,但是_source中存在该字段;
- Dynamic 设置为struct时,新增字段时,会报错,即不能动态新增字段,需要单独利用mapping来设置
5.Dynamic Mapping的Demo示例
1.Dynamic Mapping的自动创建demo
PUT my_mapping_test/_doc/1
{
"name":"zhangsan",
"age": 12,
"isMale": true,
"isFemale": "false",
"createTime":"2021-02-18T18:58:59.103Z",
"uid": "10001",
"height":178
}
通过上面的创建,我们查看mapping:
GET my_mapping_test/_mapping
得到结果如下:
{
"my_mapping_test" : {
"mappings" : {
"properties" : {
"age" : {
"type" : "long"
},
"createTime" : {
"type" : "date"
},
"height" : {
"type" : "long"
},
"isFemale" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
},
"isMale" : {
"type" : "boolean"
},
"name" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
},
"uid" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
}
}
}
}
}