本文介绍Elasticsearch零宕机时间更新索引配置映射内容的方法,包括字段类型、分词器、分片数等。方法原理就是,利用别名机制,给索引配置别名,所有应用程序都通过别名访问索引。重建索引,通过索引原名将原索引导入新建索引。再为新索引配置相同的别名。确认成功导入后,则删掉老索引。实现配置参数更新。
注意:
以下所有操作都是基于一个前提:在建原始索引的时候,给原始索引创建了别名
PUT /my_index_v1 //创建索引 my_index_v1
PUT /my_index_v1/_alias/my_index //设置 my_index为 my_index_v1
1. 原始的索引bank,类型:account,mapping如下
{
"settings": {
"number_of_shards": 5
},
"mappings": {
"account": {
"properties": {
"balance": {
"type": "long"
},
"account_number": {
"type": "long"
},
"email": {
"type": "string"
},
"address": {
"type": "string"
},
"age": {
"type": "long"
},
"state": {
"type": "string"
},
"employer": {
"type": "string"
},
"lastname": {
"type": "string"
},
"gender": {
"type": "string"
},
"firstname": {
"type": "string"
},
"city": {
"type": "string"
}
}
}
}
}
2.新建一个空的索引bak_bak,类型:account,,分片20,balance,account_number,age字段由long改成了string类型,具有最新的、正确的配置
{
"settings": {
"number_of_shards": 20
},
"mappings": {
"account": {
"properties": {
"balance": {
"type": "string"
},
"account_number": {
"type": "string"
},
"email": {
"type": "string"
},
"address": {
"type": "string"
},
"age": {
"type": "string"
},
"state": {
"type": "string"
},
"employer": {
"type": "string"
},
"lastname": {
"type": "string"
},
"gender": {
"type": "string"
},
"firstname": {
"type": "string"
},
"city": {
"type": "string"
}
}
}
}
}
3.使用java API迁移索引,主要配置参数如下:
String searchHost = "192.168.11.51";// 旧索引地址
int searchPort = 9300;// 旧索引端口
String searchIndexName = "bank";// 旧索引名字
String searchType = "account";// 旧索引类型
String newIndexName = "bak_bank";// 新索引名字
String newType = "account";// 新索引类型
// 过滤器根据实际情况来定义,可以有选择性的导出数据,不定义filter的话,就是导出全部数据
String filter = "{ 'query' : {'query_string' : { 'query' : 'text:blup*'} } }"
.replaceAll("'", "\"");
String basicAuthCredentials = "base64_ifrequried=";
boolean withVersion = false;
final int hitsPerPage = 2000;//bulk批量操作的内存页大小,一般1000-2500比较合适
float waitInSeconds = 0.0f;//索引线程休眠时间
// increase if you have lots of things to update
int keepTimeInMinutes = 90;
4.接下来修改alias别名的指向(如果你之前没有用alias来改mapping,纳尼就等着哭吧)
curl -XPOST localhost:8305/_aliases -d '
{
"actions": [
{ "remove": {
"alias": "mybank",
"index": "bank"
}},
{ "add": {
"alias": "mybank",
"index": "bak_bank"
}}
]
}
5.确认导入正常时,将老索引删掉
curl -XDELETE localhost:8303/store_v1