自动映射是ES提供的一个重要的特性,它将文档建立索引之前的工作全部自动化了(创建索引、定义映射类型、字段发现/定义字段);
可以通过以下方式自定义动态映射规则
1、字段动态映射:管理字段动态发现
默认情况下文档中新增了字段,es能自动发现变化并添加新字段到索引当中,这个特性可以通过设置dynamic参数为false(忽略新字段)或strict(抛异常)来禁止;
假设dynamic参数映射为true,以下简单规则用于确定新增字段的类型:
序号 | json数据类型 | ES数据类型 |
---|---|---|
1 | null | 没有字段添加 |
2 | true或false | boolean字段 |
3 | 浮点数 | float字段 |
4 | integer | long字段 |
5 | object | object字段 |
6 | array | 取决于数组第一个非空值的类型 |
7 | string | date/double/long/text(新增一个keyword的子级字段)类型中匹配的一个 |
这些规则仅适用于字段数据类型,其他的类型(复杂类型、geo类型、特殊类型等)必须要显式指定;
日期检测
若date_detection参数启用(默认启用),当新增加的字段内容能够匹配dynamic_date_formates则认定该字段类型为date类型;
dynamic_date_formates默认格式:[“strict_date_optional_time”,“yyyy/MM/dd HH:mm:ss Z||yyyy/MM/dd Z”]
PUT dyn_date_detection_1_index/_doc/1
{
"create_time":"2020/05/31"
}
GET dyn_date_detection_1_index/_mapping
{
"dyn_date_detection_1_index" : {
"mappings" : {
"properties" : {
"create_time" : {
"type" : "date",
"format" : "yyyy/MM/dd HH:mm:ss||yyyy/MM/dd||epoch_millis"
}
}
}
}
}
禁用日期自动检测
PUT dyn_date_detection_2_index
{
"mappings": {
"date_detection": false
}
}
PUT dyn_date_detection_2_index/_doc/1
{
"create_time":"2020/05/31"
}
//create_time类型被映射为text
GET dyn_date_detection_2_index/_mapping
{
"dyn_date_detection_2_index" : {
"mappings" : {
"date_detection" : false,
"properties" : {
"create_time" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
}
}
}
}
}
数值类型自动检测
因为json支持原生浮点数和整数数据类型,一些应用或编程语言可能会将数值渲染为字符串;通常正确的解决方案是显式映射这些字段,不过启用数字检测(默认为禁用状态)可以自动执行此操作:
PUT dyn_numeric_detection_index
{
"mappings": {
"numeric_detection": true
}
}
PUT dyn_numeric_detection_index/_doc/1
{
"float_define":"1.0",
"integer_define":"1"
}
GET dyn_numeric_detection_index/_mapping
2、动态映射模板:配置新增字段的映射规则
动态模板允许自定义映射规则:
1)、ES结合match_mapping_type自动检测数据类型;
2)、根据字段名称使用match、unmatch或者match_pattern进行匹配;
3)、根据字段全限定路径使用path_match和path_unmatch进行匹配;
原始字段名可使用模板变量{name}代替,检测到的数据类型可使用模板变量{dynamic_type}代替;
动态映射的字段要求新增的字段有确定的值(null或空数组不满足),这也就意味着如果在动态模板字段中设置了null_value参数,该参数要在配置该参数字段首次有确定值的时被应用;
动态模板映射模板格式:
"dynamic_templates": [
{
//模板名称可以自定义
"my_template_name": {
//match conditions可包含的类型:match_maooing_type,match,match_pattern,unmatch,path_match,path_unmatch
... match conditions ...
//匹配的字段应该映射的类型
"mapping": {