旧索引信息如下:
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接口,例如添加字段品牌名称brandName如下:
|
POST /test_v1/item/_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" } }
]
}
|
4,删除旧索引
添加或迁移别名后删除旧索引: