Elasticsearch核心技术与实战学习笔记 第三章 Index Template和Dynamic Template

一 序

   本文属于极客时间Elasticsearch核心技术与实战学习笔记系列。

管理多个索引

集群上的索引会越来越多,例如,你会为日志每天创建个索引
使用多个索引可以让你的更好的管理的你数据,提高性能

二 Index Template

Index Templates 帮助你设定 Mapping 和 Settings,并按照一定的规则,自动匹配到新创建的索引之上
模板仅在一个索引被新创建时,才会产生作用。修改模板不会影响已创建的索引
可以设定多个索引模板,这些设置会被 merge 在一起
可以指定 order 的数值,控制 merging 的过程

两个 Index Templates

 右边的mapping设置日期探测关闭,数字探测打开。

Index Template 工作方式

当一个索引被新创建时
应用 Elasticsearch默认的 settings 和 mappings
应该 order 数值低的 Index Template 中的设定
应用 order 高的 Index Template 中的设定,之前的设定会被覆盖
应用创建索引时,用户所指定的 Settings 和 Mappings,并覆盖之前模板中的设定

Demo

回归下上节课,数字字符串被映射成text,日期字符串被映射成日期

创建两个template 

#Create a default template
PUT _template/template_default
{
  "index_patterns": ["*"],
  "order" : 0,
  "version": 1,
  "settings": {
    "number_of_shards": 1,
    "number_of_replicas":1
  }
}
PUT /_template/template_test
{
    "index_patterns" : ["test*"],
    "order" : 1,
    "settings" : {
    	"number_of_shards": 1,
        "number_of_replicas" : 2
    },
    "mappings" : {
    	"date_detection": false,
    	"numeric_detection": true
    }
}

写入信息并查看

{
  "testtemplate" : {
    "settings" : {
      "index" : {
        "creation_date" : "1589806561677",
        "number_of_shards" : "1",
        "number_of_replicas" : "2",
        "uuid" : "tlXRf0rtR9C43uvLGzsaeA",
        "version" : {
          "created" : "7020099"
        },
        "provided_name" : "testtemplate"
      }
    }
  }
}
settings 的number_of_replicas=2.符合之前的设置。

自定义覆盖掉之前的。

三 Dynamic Template

根据 Elasticsearch 识别的数据类型,结合字段名称,来动态设定字段类型

  • 所有的字符串类型都设定称 Keyword,或者关闭 keyword 字段
  • is 开头的字段都设置成 boolean
  • long_ 开头的都设置成 long 类型

这是官网说明:

  • Dynamic Template 是定义在某个索引的 Mapping 中
  • Template 有个名字
  • 匹配规则是个一个数组
  • 为匹配到字段设置 Mapping

demo;

 

设置新的 my_index

DELETE my_index
#结合路径
PUT my_index
{
  "mappings": {
    "dynamic_templates": [
      {
        "full_name": {
          "path_match":   "name.*",
          "path_unmatch": "*.middle",
          "mapping": {
            "type":       "text",
            "copy_to":    "full_name"
          }
        }
      }
    ]
  }
}


PUT my_index/_doc/1
{
  "name": {
    "first":  "John",
    "middle": "Winston",
    "last":   "Lennon"
  }
}
GET my_index/_search?q=full_name:John

上面设置新的my_index,并插入一条数据,然后去搜索有返回结果

{
  "took" : 571,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 1,
      "relation" : "eq"
    },
    "max_score" : 0.2876821,
    "hits" : [
      {
        "_index" : "my_index",
        "_type" : "_doc",
        "_id" : "1",
        "_score" : 0.2876821,
        "_source" : {
          "name" : {
            "first" : "John",
            "middle" : "Winston",
            "last" : "Lennon"
          }
        }
      }
    ]
  }
}

猜你喜欢

转载自blog.csdn.net/bohu83/article/details/106200835
今日推荐