Use Tablestore SDK for Python to atomically increment or decrement integer attribute columns at the row level.
Prerequisites
Install the Tablestore SDK for Python and initialize a client. Atomic counters require version 5.1.0 or later. We recommend that you use the latest version.
Function description
Call update_row and set the attribute column operation to INCREMENT to atomically change an integer attribute column. A positive value increments the column, and a negative value decrements it.
def update_row(
self,
table_name,
row,
condition,
return_type=None,
transaction_id=None,
)
The following example atomically increments the counter attribute column by 5.
primary_key = [("partition", "device"), ("id", 1)]
attribute_columns = {"INCREMENT": [("counter", 5)]}
row = Row(primary_key, attribute_columns)
condition = Condition(RowExistenceExpectation.EXPECT_EXIST)
consumed, return_row = client.update_row(
"example_table",
row,
condition,
)
print("Write CU: %s" % consumed.write)
The update_row method in Tablestore SDK for Python does not directly return the value after an atomic counter operation. To obtain the new value, call get_row after the update.
Parameters
An atomic counter operation contains the following key parameters.
|
Name |
Type |
Description |
|
table_name (required) |
|
The name of the table. |
|
primary_key (required) |
|
The primary key of the target row. Specify all primary key columns. The primary key schema must match that of the table. |
|
column_name (required) |
|
The name of the attribute column on which to perform the atomic counter operation. Only integer attribute columns are supported. |
|
value (required) |
|
The amount by which to change the attribute column value. A positive value increments the column, and a negative value decrements it. |
|
condition (required) |
|
The update condition. For more information, see Use conditional updates. |
|
transaction_id (optional) |
|
The local transaction ID. Specify this parameter only for atomic counter operations in a local transaction. |
Limits
Only integer attribute columns are supported. If the target column does not exist, its initial value is treated as
0. If the column exists but is not an integer, the server returnsOTSParameterInvalid.The change amount can be positive or negative, but the result cannot exceed the range of a signed 64-bit integer. Otherwise, the server returns
OTSParameterInvalid.An atomic counter operation applies only to the latest version and does not support a specified data version. The update writes a new data version.
-
In the same update, you cannot perform an atomic counter operation and another operation, such as overwrite or delete, on the same attribute column.
ImportantAn atomic counter operation can return a failure because of a network timeout or system error. A direct retry can apply the change more than once and produce an inaccurate count. For strict accuracy, read the current value and use a conditional update to write the new value.