背景
Elasticsearch 是⼀个实时的分布式搜索引擎,为⽤户提供搜索服务,当我们决定存储某种数据时,在创建索引的时候需要将数据结构完整确定下来,于此同时索引的设定和很多固定配置将⽤不能改变。当需要改变数据结构时,就需要重新建⽴索引,为此, Elastic 团队提供了很多辅助⼯具帮助开发⼈员进⾏重建索引。
步骤说明
1、nba取⼀个别名nba_latest, nba_latest作为对外使⽤
2、新增⼀个索引 nba_20220101 ,结构复制于 nba 索引,根据业务要求修改字段3、将 nba 数据同步到 nba_202201014、给 nba_20220101 添加别名 nba_latest ,删除 nba 别名 nba_latest5、删除 nba 索引
步骤实操:
我们对外提供访问nba索引时使⽤的是nba_latest别名
新增⼀个索引(⽐如修改字段类型,jerseyNo改成keyword类型)
PUT /nba_20220101
{
"mappings": {
"properties": {
"age": {
"type": "integer"
},
"birthDay": {
"type": "date"
},
"birthDayStr": {
"type": "keyword"
},
"code": {
"type": "text"
},
"country": {
"type": "keyword"
},
"countryEn": {
"type": "keyword"
},
"displayAffiliation": {
"type": "text"
},
"displayName": {
"type": "text"
},
"displayNameEn": {
"type": "text"
},
"draft": {
"type": "long"
},
"heightValue": {
"type": "float"
},
"jerseyNo": {
"type": "keyword"
},
"playYear": {
"type": "long"
},
"playerId": {
"type": "keyword"
},
"position": {
"type": "text"
},
"schoolType": {
"type": "text"
},
"teamCity": {
"type": "text"
},
"teamCityEn": {
"type": "text"
},
"teamConference": {
"type": "keyword"
},
"teamConferenceEn": {
"type": "keyword"
},
"teamName": {
"type": "keyword"
},
"teamNameEn": {
"type": "keyword"
},
"weight": {
"type": "text"
}
}
}
}
将旧索引数据copy到新索引(同步copy,异步copy)
同步等待,接⼝将会在 reindex 结束后返回
POST / _reindex{
"source": {
"index": "nba"
},
"dest": {
"index": "nba_20220101"
}
}
异步执⾏,如果 reindex 时间过⻓,建议加上 wait_for_completion=false 的参数条件,这样 reindex 将直接返回 taskId
POST / _reindex ? wait_for_completion = false{
"source": {
"index": "nba"
},
"dest": {
"index": "nba_20220101"
}
}
-
替换别名
POST / _aliases{
"actions": [
{
"add": {
"index": "nba_20220101",
"alias": "nba_latest"
}
},
{
"remove": {
"index": "nba",
"alias": "nba_latest"
}
}
]
}
-
删除旧索引
DELETE / nba
-
通过别名访问新索引
POST /nba_latest/_search{
"query": {
"match": {
"displayNameEn": "james"
}
}
}