Local transactions (partition key-based transactions) can be used to specify that the operations on a partition key are atomic, meaning that operations based on the specified partition key either succeed or fail. The isolation level of the local transaction is serializable.
OTSClient#start_local_transactionto start the transaction on the specified partition key. The returned value is the transaction ID that can be used to perform operations within the transaction. The following operations are supported for local transactions:
Create a client
client = OTSClient( OTS_ENDPOINT, # endpoint OTS_ACCESS_KEY_ID, # access_key_id OTS_ACCESS_KEY_SECRET, # access_key_secret OTS_INSTANCE) # The name of the instance.
Start, submit, and abort local transactions
- Start a local transaction
You can use
OTSClient#start_local_transactionto start a local transaction.
# Start a local transaction for the partition key PK0. key = [('PK0', 1)] # The returned value of the start_local_transaction method is the transaction ID. transaction_id = client.start_local_transaction(table_name, key)
- Submit a local transaction
# Submit the local transaction. client.commit_transaction(transaction_id)
- Abort a local transaction
Perform operations using the transaction ID
- Perform write operations through local transactions
The following code provides an example on how to call the PutRow operation within a transaction. You must perform write operations within the partition key on which the transaction is started. Otherwise, an exception is returned.
primary_key = [('PK0', 1), ('PK1', 'transaction')] attribute_columns = [('value', 'origion value')] row = Row(primary_key, attribute_columns) condition = Condition(RowExistenceExpectation.IGNORE) consumed, return_row = client.put_row(table_name, row, condition)
- Perform read operations through local transactions
You can perform read operations within a transaction. For example, you must read data before you modify the data. The following code provides an example on how to call the GetRow operation within a transaction. To use a local transaction, you must call the GetRow operation within the partition key on which the transaction is started.
primary_key = [('PK0', 1), ('PK1', 'transaction')] columns_to_get = ['value'] consumed, return_row, next_token = client.get_row( table_name, primary_key, columns_to_get, None, 1, None, None, None, None, transaction_id ) for att in return_row.attribute_columns: print ('\tname:%s\tvalue:%s' % (att, att))