Elasticsearch第四篇:索引别名、添加或修改映射规则
- 2020 年 8 月 10 日
- 筆記
- elasticsearch
项目中经常出现的问题,例如添加字段、修改字段,那原先的索引规则就要跟着改变,最好是一开始就给索引一个别名,修改字段时新增映射,然后将笔名指向新的映射,当然需要将之前的索引搬迁到新的映射当中。
1、获取映射信息(例如索引库是db_student)
GET http://localhost:9200/db_student/_mapping
这时可以看到返回结果:
{ "db_student": { "mappings": { "properties": { "chinese": { "type": "integer", "store": true }, "class": { "type": "integer", "store": true }, "english": { "type": "integer", "store": true }, "math": { "type": "integer", "store": true }, "name": { "type": "text", "store": true }, "school": { "type": "text", "store": true, "analyzer": "ik_max_word" } } } } }
这正是上一篇我们设置的映射规则,现在我们想要增加一列 desc ,用来保存学生的自我介绍介绍信息,首先,我们可以为 索引库 db_student 取一个别名 student 。
2、为旧索引库 db_student 起一个别名 student
PUT http://localhost:9200/db_student/_alias/student
此时,再查一下就索引库有哪些别名:
GET http://localhost:9200/db_student/_alias
呈现的效果是:
{ "db_student": { "aliases": { "student": {} } } }
此时,别名已经生效。
3、建立新的索引库 db_student_v1,在原索引库的基础上加上 desc 这一新的字段,并且使用 ik 分词
PUT http://localhost:9200/db_student_v1 { "mappings": { "properties": { "class": { "type": "integer", "store": true, "index":true }, "chinese": { "type": "integer", "store": true, "index":true }, "english": { "type": "integer", "store": true, "index":true }, "math": { "type": "integer", "store": true, "index":true }, "name": { "type": "text", "store": true, "index":true }, "school": { "type": "text", "store": true, "index":true, "analyzer":"ik_max_word" }, "desc": { "type": "text", "store": true, "index":true, "analyzer":"ik_max_word" } } } }
4、数据搬迁,现在将索引库 db_student 的数据搬到新的索引库 db_student_v1
POST http://localhost:9200/_reindex { "conflicts": "proceed", "source": { "index": "db_student" }, "dest": { "index": "db_student_v1", "op_type": "create", "version_type": "external" } }
5、更改别名,将旧版索引库 db_student 的别名去除,将别名指向新版的索引库 db_student_v1
去除旧版索引库 db_student 的别名:
POST http://localhost:9200/_aliases { "actions": [ { "remove": { "index": "db_student", "alias": "student" } } ] }
为新版索引库 db_student_v1 加上别名:
POST http://localhost:9200/_aliases { "actions": [ { "add": { "index": "db_student_v1", "alias": "student" } } ] }
此时就可以统一按照别名 student 来进行上一篇的所有查询动作。