全部產品
Search
文件中心

Tablestore:動態修改 Schema

更新時間:Aug 08, 2026

使用 Tablestore Go SDK 基於源多元索引建立灰階索引,在不中斷資料表讀寫的情況下調整索引 Schema。

前提條件

安裝Tablestore Go SDK並初始化用戶端。

功能說明

動態修改 Schema 通過建立灰階索引、同步資料、灰階驗證和交換索引完成。過程中不需要停止資料表讀寫,使用源索引名稱的查詢代碼也無需修改。完整流程如下:

  1. 基於源索引建立包含完整新 Schema 的灰階索引。

  2. 等待灰階索引進入增量同步處理並追平源索引。

  3. 按需分配查詢流量,驗證新 Schema 的查詢結果。

  4. 確認結果符合預期後交換索引。

  5. 觀察一段時間,確認運行正常後刪除指向舊 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 和同步狀態。SyncPhaseINCR 表示已進入增量同步處理,但在分配流量前仍需確認同步進度已追平源索引。

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

要與源索引交換指向的灰階索引名稱。