ElasticSearch索引重建
ElasticSearch索引一旦建立,便不可修改索引字段類型(允許增加或者刪除該字段)
例如從Integer類型修改為long類型,這是不被允許的,錯誤信息如下:
1 { 2 "error" : { 3 "root_cause" : [ 4 { 5 "type" : "illegal_argument_exception", 6 "reason" : "mapper [age] cannot be changed from type [integer] to [long]" 7 } 8 ], 9 "type" : "illegal_argument_exception", 10 "reason" : "mapper [age] cannot be changed from type [integer] to [long]" 11 }, 12 "status" : 400 13 }
因此,如果項目中有需求需要修改ElasticSearch的索引中字段的類型,則需要重建索引
以下介紹通過別名_aliase的方式實現不停機的重建ElasticSearch索引
前提:項目中使用的索引的別名,例如索引是index_user ,使用的是別名index_user_latest
索引重建的步驟:
step1: 創建新索引index_user_20210123並初始化映射關系,映射也就是包含了修改后的字段類型;
step2: 使用 _reindex 將原索引index_user中的數據,導入到新索引index_user_20210123;
step3: aliases actions修改別名: 將index_user的別名index_user_latest移除,index_user_20210123新增別名index_user_latest
以上便完成了修改字段類型的數據遷移
備注:
1.舊的索引index_user 可以刪也可以不刪