全部產品
Search
文件中心

Tablestore:更新單行資料

更新時間:Mar 31, 2026

本文介紹如何通過 Python SDK 更新Table Store資料表中的單行資料,您可以更新屬性列的值、添加屬性列、刪除屬性列的某個版本或整個屬性列。

前提條件

初始化Tablestore Client

方法說明

def update_row(self, table_name, row, condition, return_type=None, transaction_id=None)

參數說明

名稱

類型

說明

table_name(必選)

str

資料表名稱。

row(必選)

Row

更新的行資料資訊,包含以下參數。

  • primary_key(必選)List[Tuple]:主鍵資訊,包括主鍵列名稱和主索引值。

    • 主鍵列資料類型包括 STRING、INTEGER 和 BINARY。

    • 寫入資料的主鍵個數和類型必須與資料表的主鍵保持一致。

  • attribute_columns(必選)dict:更新的屬性列資訊和操作類型。

condition(必選)

Condition

更新條件,詳情請參見條件更新

return_type(可選)

ReturnType

傳回型別。

  • RT_NONE:預設值,不返回資料。

  • RT_PK:返回主鍵列。

transaction_id(可選)

str

局部事務ID,用於唯一標識局部事務,詳情請參見局部事務

範例程式碼

以下範例程式碼用於修改 test_table 表中主索引值為 row1 的行資料,將屬性列 col1 的值修改為 changed_val1。

try:
    # 構造主鍵
    primary_key = [('id', 'row1')]
    # 構造更新的屬性列資料
    attribute_columns = {
        'PUT': [('col1', 'changed_val1')]
    }

    # 構造更新行資料
    row = Row(primary_key, attribute_columns)

    # 調用 update_row 方法更新行資料
    # 更新行資料時必須指定更新條件 (RowExistenceExpectation.IGNORE,表示不做行存在性判斷)
    consumed, return_row = client.update_row('test_table', row, Condition(RowExistenceExpectation.IGNORE))
    print('Read CU Cost: %s' % consumed.read)
    print('Write CU Cost: %s' % consumed.write)
except Exception as e:
    print("Update row failed with error: %s" % e)

您也可以參照範例程式碼進行以下行資料操作。

  • 添加一個屬性列。

    attribute_columns = {
        'PUT': [('col2', 'val2')]
    }
  • 設定屬性列資料版本號碼。

    attribute_columns = {
        'PUT': [('col2', 'val2', int(time.time() * 1000))]
    }
  • 刪除屬性列指定版本的資料。

    attribute_columns = {
        'DELETE': [('col2', None, 1747893563831)]
    }
  • 刪除整個屬性列資料。

    attribute_columns = {
        'DELETE_ALL': ['col2']
    }

相關文檔