美文网首页
ES 索引模板和动态模板

ES 索引模板和动态模板

作者: 鸿雁长飞光不度 | 来源:发表于2020-02-03 23:33 被阅读0次

1. Index Template(索引模板)

设定mapping和setting,并按照一定的规则自动匹配到新创建的索引上。

  • 模板仅会在第一个索引被新创建的时候才会起作用,修改模板对已经创建的索引没有影响。
  • 创建多个索引模板,模板配置会合并
  • 可以通过指定order的数值,控制合并的过程。

1.1 模板创建

案例格式

PUT /_template/template_default
{
  "index_patterns":["test*"],
  "order":1,
  "settings":{
    "number_of_shards":1,
    "number_of_replicas":2
  },
  "mappings":{
    "date_detection":false,
    "numeric_detection":true
  }
}

当索引的名字是以test开头的时候,将副本分片的数量设置为2,关闭日期检测功能,打开数字检测功能。

当一个索引被创建的时候,工作模式如下

  • 应用ES默认的settings和mappings
  • 应用order数值低的index template的设定
  • 应用高的index template的设定,并覆盖之前的设定。
  • 应用创建索引时,用户所指定的settings和mappings,并覆盖之前模板中的设定。
POST test_template/_doc
{
  "number":"1",
  "date":"2020/01/01"
}
GET test_template/_mapping

查看mapping结果符合预期

{
  "test_template" : {
    "mappings" : {
      "date_detection" : false,
      "numeric_detection" : true,
      "properties" : {
        "date" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        },
        "number" : {
          "type" : "long"
        }
      }
    }
  }
}

Dynamic Template(动态模板)

用于根据ES识别的数据类型,结合字段名称,来动态的设定字段类型。比如:

  • 所有的字符串类型都可以设定为keyword,或者关闭keyword字段。
  • is开头的设置为boolean
  • long开头的设置为long类型

说明:

  • dynamic template是定义在某个索引的mapping中的
  • template有一个名称
  • 匹配规则是一个数组
  • 为匹配到的字段设置mapping

格式案例:

PUT my_index 
{
  "mappings": {
    "dynamic_templates":[
      {
         "string_as boolean": {
          "match_mapping_type":"string",
          "match":"is*",
          "mapping":{
          "type":"boolean"
          }
        }
      },
      {
        "string_as_keyword":{
          "match_mapping_type":"string",
          "mapping":{
            "type":"keyword"
          }
        }
      }
      ]
  }
}

名称为dynamic_templates,第一个表示把is开头的字符串转换boolean值处理,第二个表示把其他的字段当成keyword。

POST my_index/_doc
{
  "is_vip":"true",
  "name":"zhangsan"
}
GET my_index/_mapping

相关文章

网友评论

      本文标题:ES 索引模板和动态模板

      本文链接:https://www.haomeiwen.com/subject/twlqxhtx.html