このトピックでは、テーブルの自動インクリメント主キー列を設定し、自動インクリメント列にデータを書き込み、Tablestore SDK for Go を使用して生成された自動インクリメント値を取得する方法について説明します。
考慮事項
自動インクリメント列に対して生成される自動インクリメント値は、パーティションキーレベルで一意であり、厳密に単調増加しますが、連続しているとは限りません。
前提条件
自動インクリメント主キー列の設定
テーブルの作成時に、パーティションキー以外の主キー列を自動インクリメントに設定できますが、既存のテーブルに対しては設定できません。
説明
整数型のパーティションキー以外の主キー列のみが自動インクリメント列になることができます。テーブルには最大で 1 つの自動インクリメント列を含めることができ、64 ビット符号付き整数の値が生成されます。
サンプルコード
次のサンプルコードは、test_table という名前のテーブルを作成します。テーブルの主キーには、パーティションキー id と自動インクリメント列 incr が含まれます。
func CreateTableSample(client *tablestore.TableStoreClient) {
tableMeta := new(tablestore.TableMeta)
tableMeta.TableName = "test_table"
tableMeta.AddPrimaryKeyColumn("id", tablestore.PrimaryKeyType_STRING)
tableMeta.AddPrimaryKeyColumnOption("incr", tablestore.PrimaryKeyType_INTEGER, tablestore.AUTO_INCREMENT)
tableOption := new(tablestore.TableOption)
tableOption.MaxVersion = 1
tableOption.TimeToAlive = -1
reservedThroughput := new(tablestore.ReservedThroughput)
createTableRequest := new(tablestore.CreateTableRequest)
createTableRequest.TableMeta = tableMeta
createTableRequest.TableOption = tableOption
createTableRequest.ReservedThroughput = reservedThroughput
_, err := client.CreateTable(createTableRequest)
if err != nil {
fmt.Println("Failed to create table with error:", err) // テーブルの作成に失敗しました:
} else {
fmt.Println("Create table finished.") // テーブルの作成が完了しました。
}
}データの書き込み
自動インクリメント列にデータを書き込むときは、値のプレースホルダーを設定する必要があります。クエリと更新のために生成された自動インクリメント値を取得するには、putRowChange の戻り値の型を ReturnType_RT_PK に設定します。
サンプルコード
次のサンプルコードは、test_table テーブルに 1 行のデータを書き込み、書き込まれた行の主キー情報を取得して出力します。
func PutRowSample(client *tablestore.TableStoreClient) {
// 主キーを構築する
putPrimaryKey := new(tablestore.PrimaryKey)
putPrimaryKey.AddPrimaryKeyColumn("id", "row1")
// 自動インクリメント列を設定する
putPrimaryKey.AddPrimaryKeyColumnWithAutoIncrement("incr")
// 書き込む行データを構築する
putRowChange := new(tablestore.PutRowChange)
putRowChange.TableName = "test_table"
putRowChange.PrimaryKey = putPrimaryKey
putRowChange.AddColumn("col1", "val1")
putRowChange.SetCondition(tablestore.RowExistenceExpectation_IGNORE)
// 書き込まれた行の主キー情報を返すように、戻り値の型を ReturnType_RT_PK に設定する
putRowChange.ReturnType = tablestore.ReturnType_RT_PK
// putRow メソッドを呼び出して行データを書き込む
putRowRequest := new(tablestore.PutRowRequest)
putRowRequest.PutRowChange = putRowChange
response, err := client.PutRow(putRowRequest)
if err != nil {
fmt.Println("Failed to put row with error:", err) // 行の書き込みに失敗しました:
} else {
// RequestId と消費された CU
fmt.Printf("RequestId: %s \n", response.RequestId)
fmt.Printf("Read CU Cost: %d \n", response.ConsumedCapacityUnit.Read) // 読み取り CU コスト:
fmt.Printf("Write CU Cost: %d \n", response.ConsumedCapacityUnit.Write) // 書き込み CU コスト:
// 返された主キー情報を取得して出力する。戻り値の型が ReturnType_RT_PK に設定されていない場合、主キー情報はデフォルトでは返されません
fmt.Println(response.PrimaryKey)
}
}