舊索引信息如下:
index:test_v1
type:item
alias:item_alias
mapping:
{
"properties": {
"itemId": {
"type": "long"
},
"itemName": {
"type": "text",
"analyzer": "ik_max_word",
"search_analyzer": "ik_smart"
}
}
}
添加字段:
使用最新的mapping直接調用putMapping接口
PUT http://xxx.xxx.xxx.xxx:9200/goods_info/_mapping
{
"properties": {
"itemId": {
"type": "long"
},
"itemName": {
"type": "text",
"analyzer": "ik_max_word",
"search_analyzer": "ik_smart"
},
"brandName": {
"type": "text",
"analyzer": "ik_max_word",
"search_analyzer": "ik_smart"
}
}
}
修改字段:
由於Elasticsearch底層使用了lucene的原因,不支持對mapping的修改,可使用索引重建的方式,步驟如下:
1,使用正確的mapping新建索引和類型
如需要將舊索引的itemId字段改爲keyword類型,則執行以下請求:
創建index:
PUT /test_v2
設置mapping:
POST /test_v2/item/_mapping
{
"properties": {
"itemId": {
"type": "keyword"
},
"itemName": {
"type": "text",
"analyzer": "ik_max_word",
"search_analyzer": "ik_smart"
}
}
}
2,使用reindex api將舊索引數據導入新索引
索引重建後可使用reindex命令遷移數據,如將test_v1數據遷移至test_v2請求如下:
POST _reindex
{
"source": {
"index": "test_v1",
"type": "item"
},
"dest": {
"index": "test_v2",
"type": "item"
}
}
3,爲新索引添加別名
爲索引添加別名後,在程序代碼中可以使用固定別名查詢動態的索引名稱,然後進行查詢,如此索引重建則不會引起程序的變動
添加別名請求:
POST /_aliases
{
"actions": [
{ "add": {
"alias": "item_alias",
"index": "test_v2"
}}
]
}
將舊索引別名遷移到新索引請求:
POST /_aliases
{
"actions" : [
{ "remove" : { "index" : "test_v1", "alias" : "item_alias" } },
{ "add" : { "index" : "test_v2", "alias" : "item_alias" } }
]
}