更新单行数据

更新时间:
复制 MD 格式

Go SDK 可新增、修改或删除宽表模型数据表中一行数据的属性列。

前提条件

安装Tablestore Go SDK并初始化客户端。

功能说明

调用 UpdateRow 更新指定主键行的属性列。可以新增或覆盖属性列的数据版本,也可以删除指定版本或整列数据;可通过 Condition 控制更新是否执行。

func (tableStoreClient *TableStoreClient) UpdateRow(request *UpdateRowRequest) (*UpdateRowResponse, error)

以下示例更新 example_table 中主键值为 row1 的行:修改 status 属性列,并删除 temporary 属性列。

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

change := &tablestore.UpdateRowChange{
    TableName:  "example_table",
    PrimaryKey: primaryKey,
}
change.PutColumn("status", "active")
change.DeleteColumn("temporary")
change.SetCondition(tablestore.RowExistenceExpectation_EXPECT_EXIST)

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

参数说明

UpdateRowRequest 包含以下参数。

名称

类型

说明

UpdateRowChange(必选)

*UpdateRowChange

单行更新配置。

行变更

UpdateRowChange 包含以下参数。

名称

类型

说明

TableName(必选)

string

数据表名称。

PrimaryKey(必选)

*PrimaryKey

行主键。主键列的名称、顺序和类型必须与数据表的主键结构一致。

Columns(必选)

[]ColumnToUpdate

属性列更新操作。可通过 PutColumnPutColumnWithTimestampDeleteColumnDeleteColumnWithTimestamp 添加操作。

Condition(必选)

*RowCondition

更新条件。可设置行存在性条件和列条件。更多信息,请参见条件更新

TransactionId(可选)

*string

局部事务 ID。仅在局部事务内更新数据时设置。更多信息,请参见局部事务

ReturnType(可选)

ReturnType

原子计数器返回类型。调用 SetReturnIncrementValue 后设置为 ReturnType_RT_AFTER_MODIFY

ColumnNamesToReturn(可选)

[]string

原子计数操作后要返回新值的属性列名称。

场景示例

指定数据版本号

调用 PutColumnWithTimestamp 写入指定版本的属性列,或调用 DeleteColumnWithTimestamp 删除指定版本。

timestamp := time.Now().UnixMilli()
change.PutColumnWithTimestamp("score", int64(95), timestamp)
change.DeleteColumnWithTimestamp("legacy_status", timestamp)