Tablestore SDK for Python を使用して行を書き込み、必要に応じて書き込み条件、データバージョン、またはローカルトランザクションを指定します。
前提条件
Tablestore SDK for Python をインストールし、クライアントを初期化します。
機能説明
put_row を呼び出して行を書き込みます。プライマリキーがすでに存在する場合、このメソッドは行を上書きします。存在しない場合は、新しい行を作成します。
def put_row(
self,
table_name,
row,
condition=None,
return_type=None,
transaction_id=None,
)
次の例では、プライマリキーが [("partition", "device"), ("id", 1)] の行を example_table に書き込みます。
primary_key = [("partition", "device"), ("id", 1)]
attribute_columns = [("name", "thermometer"), ("status", "online")]
row = Row(primary_key, attribute_columns)
condition = Condition(RowExistenceExpectation.IGNORE)
consumed, return_row = client.put_row(
"example_table",
row,
condition,
)
print("Write CU: %s" % consumed.write)
パラメーター
put_row メソッドには、次のパラメーターが含まれます。
|
名前 |
型 |
説明 |
|
table_name (必須) |
|
テーブルの名前。 |
|
row (必須) |
|
書き込むプライマリキーと属性列。 |
|
condition (オプション) |
|
書き込み条件。デフォルトでは、行の存在はチェックされません。詳細については、「条件付き更新の使用」をご参照ください。 |
|
return_type (オプション) |
|
戻り値の型。 |
|
transaction_id (オプション) |
|
ローカルトランザクション ID。このパラメーターは、ローカルトランザクション内の書き込みでのみ指定します。詳細については、「ローカルトランザクションの使用」をご参照ください。 |
行データ
row パラメーターは Row 型で、次のパラメーターが含まれます。
|
名前 |
型 |
説明 |
|
primary_key (必須) |
|
プライマリキー。プライマリキー列の名前、順序、数、型は、テーブルのプライマリキースキーマと一致する必要があります。 |
|
attribute_columns (オプション) |
|
属性列。各要素は |
応答
put_row は次の値を返します。
|
フィールド |
型 |
説明 |
|
consumed |
|
この操作で消費された読み取りおよび書き込みキャパシティーユニット。 |
|
return_row |
|
返される行。 |
例
複数の属性列の書き込み
次の例では、文字列型、整数型、ブール型の属性列を書き込みます。
primary_key = [("partition", "device"), ("id", 2)]
attribute_columns = [
("name", "humidity-sensor"),
("temperature", 26),
("enabled", True),
]
row = Row(primary_key, attribute_columns)
client.put_row(
"example_table",
row,
Condition(RowExistenceExpectation.IGNORE),
)
データバージョンの指定
属性列タプルの3番目の要素で、データバージョンをミリ秒単位で指定します。バージョンは、テーブルで許容されている有効なバージョン範囲内に収める必要があります。
timestamp = int(time.time() * 1000)
primary_key = [("partition", "device"), ("id", 3)]
attribute_columns = [
("status", "online", timestamp),
("temperature", 25, timestamp),
]
row = Row(primary_key, attribute_columns)
client.put_row(
"example_table",
row,
Condition(RowExistenceExpectation.IGNORE),
)
自動採番主キー値の取得
自動インクリメントプライマリキー列があるテーブルに書き込む場合、列の値を PK_AUTO_INCR に、return_type を RT_PK に設定します。要件の詳細については、「自動インクリメントプライマリキー列を使用する」をご参照ください。
primary_key = [("partition", "device"), ("id", PK_AUTO_INCR)]
row = Row(primary_key, [("name", "pressure-sensor")])
consumed, return_row = client.put_row(
"example_table",
row,
Condition(RowExistenceExpectation.IGNORE),
ReturnType.RT_PK,
)
print(return_row.primary_key)