索引重建方案
我们通过创建新索引的方式来解决现有索引字段类型问题:
- 创建新索引并设置正确的mapping映射
- 使用POST /_reindex迁移数据
- 验证数据和mapping映射
- 删除原错误索引
- 创建别名指向老索引名称
实现步骤
- 模拟问题索引创建(将user_id错误设置为keyword类型)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| DELETE /new_test-users
DELETE /test-users
PUT /test-users
{
"mappings": {
"_doc": {
"properties": {
"user_id": {
"type": "keyword"
}
}
}
}
}
|
- 填充测试数据
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| POST /test-users/_doc
{
"user_id": "123",
"name": "张三",
"age": 25,
"location": "北京"
}
POST /test-users/_doc
{
"user_id": "456",
"name": "456",
"age": 456,
"location": "456"
}
|
- 验证索引数据和结构
1
2
| GET /test-users/_search
GET /test-users/_mapping
|
- 尝试直接修改mapping(会报错)
1
2
3
4
5
6
7
8
| PUT /test-users/_doc/_mapping
{
"properties": {
"user_id": {
"type": "long"
}
}
}
|
- 创建新索引并设置正确字段类型
1
2
3
4
5
6
7
8
9
10
11
12
| PUT /new_test-users
{
"mappings": {
"_doc": {
"properties": {
"user_id": {
"type": "long"
}
}
}
}
}
|
- 迁移数据到新索引
1
2
3
4
5
6
7
8
9
| POST /_reindex
{
"source": {
"index": "test-users"
},
"dest": {
"index": "new_test-users"
}
}
|
- 验证新索引数据
1
2
| GET /new_test-users/_search
GET /new_test-users/_mapping
|
- 删除原索引
- 设置别名保持兼容性
1
| PUT /new_test-users/_alias/test-users
|
- 最终验证
1
2
3
4
5
6
7
8
9
10
| GET /test-users/_mapping
GET /test-users/_alias
GET /test-users/_search
{
"query": {
"term": {
"user_id": "123"
}
}
}
|