使用 Tablestore Go SDK 基于源多元索引创建灰度索引,在不中断数据表读写的情况下调整索引 Schema。
前提条件
安装Tablestore Go SDK并初始化客户端。
功能说明
动态修改 Schema 通过创建灰度索引、同步数据、灰度验证和交换索引完成。过程中不需要停止数据表读写,使用源索引名称的查询代码也无需修改。完整流程如下:
基于源索引创建包含完整新 Schema 的灰度索引。
等待灰度索引进入增量同步并追平源索引。
按需分配查询流量,验证新 Schema 的查询结果。
确认结果符合预期后交换索引。
-
观察一段时间,确认运行正常后删除指向旧 Schema 的灰度索引。
重要灰度索引名称必须以
_reindex结尾。流程中索引指向和流量权重会变化,请勿直接使用灰度索引名称作为长期查询入口。同一时间最多重建 5 个索引;开始下一批前,等待当前批次追平源索引或完成索引切换。
1. 创建灰度索引
sourceIndexName := "example_index"
reindexName := "example_index_reindex"
newSchema := []*tablestore.FieldSchema{
{
FieldName: proto.String("category"),
FieldType: tablestore.FieldType_KEYWORD,
Index: proto.Bool(true),
},
{
FieldName: proto.String("new_field"),
FieldType: tablestore.FieldType_KEYWORD,
Index: proto.Bool(true),
},
}
_, err := client.CreateSearchIndex(&tablestore.CreateSearchIndexRequest{
TableName: "example_table",
IndexName: reindexName,
SourceIndexName: &sourceIndexName,
IndexSchema: &tablestore.IndexSchema{
FieldSchemas: newSchema,
},
})
if err != nil {
log.Fatal(err)
}
请求成功后,通过查询多元索引信息检查灰度索引的 Schema 和同步状态。SyncPhase 为 INCR 表示已进入增量同步,但在分配流量前仍需确认同步进度已追平源索引。
2. 配置查询流量
weights := []*tablestore.QueryFlowWeight{
{IndexName: "example_index", Weight: 50},
{IndexName: "example_index_reindex", Weight: 50},
}
_, err := client.UpdateSearchIndex(&tablestore.UpdateSearchIndexRequest{
TableName: "example_table",
IndexName: "example_index",
QueryFlowWeights: weights,
})
if err != nil {
log.Fatal(err)
}
先使用少量查询流量验证新 Schema,再逐步提高灰度索引权重。两个索引的 Weight 之和必须为 100。
3. 交换索引
reindexName := "example_index_reindex"
_, err := client.UpdateSearchIndex(&tablestore.UpdateSearchIndexRequest{
TableName: "example_table",
IndexName: "example_index",
SwitchIndexName: &reindexName,
})
if err != nil {
log.Fatal(err)
}
交换后,源索引名称指向新 Schema,灰度索引名称指向旧 Schema。确认新索引运行正常并观察一段时间后,再删除灰度索引。
参数说明
创建灰度索引
|
名称 |
类型 |
说明 |
|
TableName(必选) |
string |
数据表名称。 |
|
IndexName(必选) |
string |
灰度索引名称,必须以 _reindex 结尾。 |
|
SourceIndexName(必选) |
*string |
源索引名称。 |
|
IndexSchema(必选) |
*tablestore.IndexSchema |
变更后的完整索引结构。字段、路由和预排序参数请参见创建多元索引。 |
|
TimeToLive(可选) |
*int32 |
灰度索引生命周期。取值和约束请参见生命周期管理。 |
配置流量和交换索引
|
名称 |
类型 |
说明 |
|
TableName(必选) |
string |
数据表名称。 |
|
IndexName(必选) |
string |
源索引名称。 |
|
QueryFlowWeights(可选) |
[]*tablestore.QueryFlowWeight |
源索引和灰度索引的流量权重列表。 |
|
SwitchIndexName(可选) |
*string |
要与源索引交换指向的灰度索引名称。 |