全部產品
Search
文件中心

Tablestore:條件更新

更新時間:Aug 13, 2026

Go SDK 可為行寫入、更新或刪除操作設定判斷條件,僅在目標行滿足條件時執行操作。

前提條件

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

功能說明

條件更新包含行存在性條件和列條件,兩者可以獨立使用或組合使用。通過 PutRowChangeUpdateRowChangeDeleteRowChangeSetConditionSetColumnCondition 設定條件,也可以將這些行變更對象加入 BatchWriteRow 請求。條件不滿足時,服務端返回錯誤且不修改資料。

  • 行存在性條件用於判斷目標行是否存在,包括忽略判斷、期望行存在和期望行不存在。

  • 列條件用於比較單列值,或通過邏輯運算組合多個列條件。單列條件也支援主鍵列,但不支援列與列或常量與常量比較。單次更新最多包含 10 個列條件。

以下樣本僅在目標行存在且 score 列值為 30 時更新 status 列。

primaryKey := &tablestore.PrimaryKey{}
primaryKey.AddPrimaryKeyColumn("id", "row1")

change := &tablestore.UpdateRowChange{
    TableName:  "example_table",
    PrimaryKey: primaryKey,
}
change.PutColumn("status", "processed")
change.SetCondition(tablestore.RowExistenceExpectation_EXPECT_EXIST)
change.SetColumnCondition(
    tablestore.NewSingleColumnCondition("score", tablestore.CT_EQUAL, int64(30)),
)

_, err := client.UpdateRow(&tablestore.UpdateRowRequest{UpdateRowChange: change})
if err != nil {
    log.Fatal(err)
}

參數說明

行存在性條件

調用 SetCondition 設定 RowExistenceExpectation

名稱

類型

說明

expectation(必選)

RowExistenceExpectation

行存在性條件。取值範圍:RowExistenceExpectation_IGNORE,不判斷目標行是否存在;RowExistenceExpectation_EXPECT_EXIST,僅當目標行存在時滿足條件;RowExistenceExpectation_EXPECT_NOT_EXIST,僅當目標行不存在時滿足條件。

單列條件

調用 NewSingleColumnCondition(columnName, comparator, value) 建立單列條件。SingleColumnCondition 包含以下參數。

名稱

類型

說明

ColumnName(必選)

*string

要判斷的列名稱。可以是屬性列或主鍵列。

Comparator(必選)

*ComparatorType

關係運算子。支援 CT_EQUALCT_NOT_EQUALCT_GREATER_THANCT_GREATER_EQUALCT_LESS_THANCT_LESS_EQUAL

ColumnValue(必選)

interface{}

用於比較的常量值。

FilterIfMissing(可選)

bool

目標行不包含判斷列時是否視為不滿足條件。預設值為 false,即視為滿足條件。

LatestVersionOnly(可選)

bool

是否只判斷最新版本。預設值為 false,即任意版本滿足條件即視為滿足。

組合條件

調用 NewCompositeColumnCondition(lo) 建立組合條件,並調用 AddFilter 添加子條件。子條件可以是單列條件或嵌套的組合條件。CompositeColumnValueFilter 包含以下參數。

名稱

類型

說明

Operator(必選)

LogicalOperator

邏輯運算子。LO_ANDLO_OR 至少需要兩個子條件,LO_NOT 只能包含一個子條件。

Filters(必選)

[]ColumnFilter

參與邏輯運算的子條件。

情境樣本

使用組合條件更新資料

以下樣本僅在 score >= 60status 等於 pending 時執行更新。

condition := tablestore.NewCompositeColumnCondition(tablestore.LO_AND)
condition.AddFilter(
    tablestore.NewSingleColumnCondition("score", tablestore.CT_GREATER_EQUAL, int64(60)),
)
condition.AddFilter(
    tablestore.NewSingleColumnCondition("status", tablestore.CT_EQUAL, "pending"),
)

change.SetCondition(tablestore.RowExistenceExpectation_EXPECT_EXIST)
change.SetColumnCondition(condition)