写入单行数据

更新时间:
复制 MD 格式

Go SDK 可向宽表模型数据表写入或更新一行数据。

前提条件

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

功能说明

调用 PutRow 向指定主键的行写入属性列。如果行已存在,将新增或覆盖相应属性列的数据版本;可通过 Condition 控制写入是否执行。

func (tableStoreClient *TableStoreClient) PutRow(request *PutRowRequest) (*PutRowResponse, error)

以下示例向 example_table 写入主键值为 row1 的一行数据。

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

change := &tablestore.PutRowChange{
    TableName:  "example_table",
    PrimaryKey: primaryKey,
}
change.AddColumn("name", "Alice")
change.AddColumn("age", int64(30))
change.SetCondition(tablestore.RowExistenceExpectation_IGNORE)

_, err := client.PutRow(&tablestore.PutRowRequest{PutRowChange: change})
if err != nil {
    log.Fatal(err)
}

参数说明

PutRowRequest 包含以下参数。

名称

类型

说明

PutRowChange(必选)

*PutRowChange

单行写入配置。

行变更

PutRowChange 包含以下参数。

名称

类型

说明

TableName(必选)

string

数据表名称。

PrimaryKey(必选)

*PrimaryKey

行主键。主键列的名称、顺序和类型必须与数据表的主键结构一致。读取或操作包含自增主键列的行时,需提供完整主键。

Columns(可选)

[]AttributeColumn

要写入的属性列。可调用 AddColumn 添加服务端生成版本号的属性列,或调用 AddColumnWithTimestamp 指定版本号。

Condition(必选)

*RowCondition

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

ReturnType(可选)

ReturnType

返回类型。默认值为 ReturnType_RT_NONE;设置为 ReturnType_RT_PK 时返回完整主键,常用于获取自增主键值。

TransactionId(可选)

*string

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

属性列

Columns[] 的类型为 AttributeColumn,包含以下参数。

名称

类型

说明

ColumnName(必选)

string

属性列名称。

Value(必选)

interface{}

属性列值。支持字符串、整数、二进制、浮点数和布尔值。

Timestamp(可选)

int64

数据版本号,单位为毫秒。未设置时由服务端自动生成。

返回值

PutRowResponse 中的业务返回字段如下。

字段

类型

说明

PrimaryKey

PrimaryKey

写入行的完整主键。仅当 ReturnType 设置为 ReturnType_RT_PK 时返回。

场景示例

指定数据版本号

以下示例分别使用当前时间和指定时间戳作为属性列的数据版本号。

currentTimestamp := time.Now().UnixMilli()
change.AddColumnWithTimestamp("status", "active", currentTimestamp)
change.AddColumnWithTimestamp("score", int64(95), int64(1758249013000))