有时候创建好的索引库需要增加,删除或者更改一些字段,又或者想修改分词器等参数,这个时候就需要保证索引变更过程中搜索服务的正常运行。
Elasticsearch 官方就此也给出了零停机重建索引方案。能够这样做的前提是你在代码中使用别名访问索引,因为零停机重建索引本质上就是复制一份索引再把别名指向新索引,这样用户就没法感知索引有没有被切换,就是所谓的零停机。
具体步骤如下:
假设你的索引库名称叫 index , 其结构如下,别名为 docs
{
"mappings": {
"properties": {
"id": {
"type": "keyword"
},
"docNumber": {
"type": "keyword"
},
"releaseDate": {
"type": "date",
"format": "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd"
},
"docName": {
"type": "keyword"
},
"docContent": {
"type": "text",
"analyzer": "ik_max_word",
"search_analyzer": "ik_smart"
}
}
},
"settings": {
"number_of_shards": 1,
"number_of_replicas": 0
}
}
需要把它改成如下结构
{
"mappings": {
"properties": {
"id": {
"type": "keyword"
},
"docNumber": {
"type": "keyword"
},
"releaseDate": {
"type": "date",
"format": "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd"
},
"docName": {
"type": "text",
"analyzer": "ik_max_word",
"search_analyzer": "ik_smart"
},
"docContent": {
"type": "text",
"analyzer": "ik_max_word",
"search_analyzer": "ik_smart"
}
}
},
"settings": {
"number_of_shards": 1,
"number_of_replicas": 0
}
}
- 首先,新建一个索引,名字需要和旧索引做区分
建索引命令如下,命令在Kibana->Management->Dev Tools 执行:
PUT /index_1
{
"mappings": {
"properties": {
"id": {
"type": "keyword"
},
"docNumber": {
"type": "keyword"
},
"releaseDate": {
"type": "date",
"format": "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd"
},
"docName": {
"type": "text",
"analyzer": "ik_max_word",
"search_analyzer": "ik_smart"
},
"docContent": {
"type": "text",
"analyzer": "ik_max_word",
"search_analyzer": "ik_smart"
}
}
},
"settings": {
"number_of_shards": 1,
"number_of_replicas": 0
}
}
- 把旧索引库的数据写入到新索引库中,执行以下命令即可
POST _reindex
{
"source": {
"index": "index"
},
"dest": {
"index": "index_1"
}
}
- 把旧索引库的别名移到新索引库中,
POST /_aliases
{
"actions": [
{
"remove": {
"index": "index",
"alias": "docs"
}
},
{
"add": {
"index": "index_1",
"alias": "docs"
}
}
]
}
- 最后把旧索引库删除,在Kibana->Management->Index Management 选择并删除即可