Tablestore提供了PutRow和UpdateRow介面用於寫入單行資料以及BatchWriteRow介面用於批量寫入資料。

前提條件

  • 已初始化Client,詳情請參見初始化
  • 已建立資料表並寫入資料。

插入單行資料

調用PutRow介面新寫入一行資料。如果該行已存在,則先刪除原行資料(原行的所有列以及所有版本的資料),再寫入新行資料。

介面

/**
 * 寫入一行資料。如果該行已存在,則先刪除原行資料(原行的所有列以及所有版本的資料),再寫入新行資料。返回該操作消耗的CU。
 * @api
 * @param [] $request 請求參數。
 * @return [] 請求返回。 
 * @throws OTSClientException 當參數檢查出錯或服務端返回校正出錯時拋出異常。
 * @throws OTSServerException 當OTS服務端返回錯誤時拋出異常。
 */
public function putRow(array $request);            

請求參數

參數 說明
table_name 資料表名稱。
condition 使用條件更新,可以設定原行的存在性條件或者原行中某列的列值條件。更多資訊,請參見條件更新
  • row_existence:行存在性條件。
    说明
    • RowExistenceExpectationConst::CONST_IGNORE表示無論此行是否存在均會插入新資料,如果之前行已存在,則寫入資料時會覆蓋原有資料。
    • RowExistenceExpectationConst::CONST_EXPECT_EXIST表示只有此行存在時才會插入新資料,寫入資料時會覆蓋原有資料。
    • RowExistenceExpectationConst::CONST_EXPECT_NOT_EXIST表示只有此行不存在時才會插入資料。
  • column_condition:列條件。
primary_key 行的主鍵。
说明
  • 設定的主鍵個數和類型必須和資料表的主鍵個數和類型一致。
  • 當主鍵為自增列時,只需將自增列的值設定為預留位置。更多資訊,請參見主鍵列自增
  • 資料表可包含1個~4個主鍵列。主鍵列是有順序的,與使用者添加的順序相同,例如PRIMARY KEY(A, B, C)與PRIMARY KEY(A, C, B)是不同的兩個主鍵結構。Tablestore會按照主鍵的大小為行排序。
  • 每一項的順序是主鍵名、主索引值PrimaryKeyValue、主鍵類型PrimaryKeyType(可選)。
  • PrimaryKeyValue可以是整數、二進位和字串。
  • PrimaryKeyType可以是INTEGER、STRING(UTF-8編碼字串)、BINARY、PK_AUTO_INCR(主鍵列自增)四種,分別用PrimaryKeyTypeConst::CONST_INTEGERPrimaryKeyTypeConst::CONST_STRINGPrimaryKeyTypeConst::CONST_BINARYPrimaryKeyTypeConst::CONST_PK_AUTO_INCR表示,對於INTEGER和STRING,可以省略,其它類型不可省略。
attribute_columns 行的屬性列。
  • 每一項的順序是屬性名稱、屬性值ColumnValue、屬性類型ColumnType(可選)、時間戳記(可選)。
  • ColumnType可以是INTEGER、STRING(UTF-8編碼字串)、BINARY、BOOLEAN、DOUBLE五種,分別用ColumnTypeConst::CONST_INTEGERColumnTypeConst::CONST_STRINGColumnTypeConst::CONST_BINARY、ColumnTypeConst::CONST_BOOLEANColumnTypeConst::CONST_DOUBLE表示,其中BINARY不可省略,其他類型都可以省略,或者設定為null。
  • 時間戳記即資料的版本號碼。更多資訊,請參見資料版本和生命週期

    資料的版本號碼可以由系統自動產生或者自訂,如果不設定此參數,則預設由系統自動產生。

    • 當由系統自動產生資料的版本號碼時,系統預設將目前時間的毫秒單位時間戳記(從1970-01-01 00:00:00 UTC計算起的毫秒數)作為資料的版本號碼。
    • 當自訂資料的版本號碼時,版本號碼需要為64位的毫秒單位時間戳記且在有效版本範圍內。
return_content 表示傳回型別。

return_type:設定為ReturnTypeConst::CONST_PK,表示返回主索引值,主要用於主鍵列自增情境。

請求格式

$result = $client->putRow([
    'table_name' => '<string>', //設定資料表名稱。
    'condition' => [
        'row_existence' => <RowExistence>,   
        'column_condition' => <ColumnCondition>
    ],
    'primary_key' => [                              //設定主鍵。
        ['<string>', <PrimaryKeyValue>], 
        ['<string>', <PrimaryKeyValue>],
        ['<string>', <PrimaryKeyValue>, <PrimaryKeyType>]
    ],  
    'attribute_columns' => [         //設定屬性列。
            ['<string>', <ColumnValue>], 
            ['<string>', <ColumnValue>, <ColumnType>],
            ['<string>', <ColumnValue>, <ColumnType>, <integer>]
    ],
    'return_content' => [
        'return_type' => <ReturnType>
    ]
]);         

響應參數

參數 說明
consumed 本次操作消耗服務能力單元的值。
capacity_unit表示使用的讀寫能力單元。
  • read:讀輸送量
  • write:寫輸送量
primary_key 主鍵的值,和請求時一致。
说明 當在請求中設定return_type為ReturnTypeConst::CONST_PK時,會返回完整的主鍵,主要用於主鍵列自增。
attribute_columns 屬性列的值,和請求時一致,目前為空白。

響應格式

[
    'consumed' => [
        'capacity_unit' => [
            'read' => <integer>,
            'write' => <integer>
        ]
    ],
    'primary_key' => [ 
        ['<string>', <PrimaryKeyValue>], 
        ['<string>', <PrimaryKeyValue>],
        ['<string>', <PrimaryKeyValue>, <PrimaryKeyType>]
    ],  
    'attribute_columns' => []
]        

樣本

  • 樣本1

    寫入10列屬性列,每列寫入1個版本,由系統自動產生資料的版本號碼(時間戳記)。

    $attr = array();
    for($i = 0; $i < 10; $i++) {
        $attr[] = ['Col'. $i, $i]; 
    }
    $request = [
        'table_name' => 'MyTable',
        'condition' => RowExistenceExpectationConst::CONST_IGNORE, //condition可以為IGNORE、EXPECT_EXIST和EXPECT_NOT_EXIST。
        'primary_key' => [ //設定主鍵。
            ['PK0', 123],
            ['PK1', 'abc']
        ],
        'attribute_columns' => $attr
    ];
    $response = $otsClient->putRow ($request);            
  • 樣本2

    寫入10列屬性列,每列寫入3個版本,自訂資料的版本號碼(時間戳記)。

    $attr = array();
    $timestamp = getMicroTime();
    for($i = 0; $i < 10; $i++) {
        for($j = 0; $j < 3; $j++) {
            $attr[] = ['Col'. $i, $j, null, $timestamp+$j];
        }
    }
    $request = [
        'table_name' => 'MyTable',
        'condition' => RowExistenceExpectationConst::CONST_IGNORE, //condition可以為IGNORE、EXPECT_EXIST和EXPECT_NOT_EXIST。
        'primary_key' => [ //設定主鍵。
            ['PK0', 123],
            ['PK1', 'abc']
        ],
        'attribute_columns' => $attr
    ];
    $response = $otsClient->putRow ($request);            
  • 樣本3

    期望原行不存在時,寫入10列屬性列,每列寫入3個版本,自訂資料的版本號碼(時間戳記)。

    $attr = array();
    $timestamp = getMicroTime();
    for($i = 0; $i < 10; $i++) {
        for($j = 0; $j < 3; $j++) {
            $attr[] = ['Col'. $i, $j, null, $timestamp+$j];
        }
    }
    $request = [
        'table_name' => 'MyTable',
        'condition' => RowExistenceExpectationConst::CONST_EXPECT_NOT_EXIST, //設定期望原行不存在時,寫入資料。
        'primary_key' => [ //設定主鍵。
            ['PK0', 123],
            ['PK1', 'abc']
        ],
        'attribute_columns' => $attr
    ];
    $response = $otsClient->putRow ($request);            
  • 樣本4

    期望原行存在且Col0列的值大於100時,寫入10列屬性列,每列寫入3個版本,自訂資料的版本號碼(時間戳記)。

    $attr = array();
    $timestamp = getMicroTime();
    for($i = 0; $i < 10; $i++) {
        for($j = 0; $j < 3; $j++) {
            $attr[] = ['Col'. $i, $j, null, $timestamp+$j];
        }
    }
    $request = [
        'table_name' => 'MyTable',
        'condition' => [
            'row_existence' => RowExistenceExpectationConst::CONST_EXPECT_EXIST,//期望原行存在。
            'column_condition' => [                  //使用條件更新,滿足條件則更新。
                'column_name' => 'Col0',
                'value' => 100,
                'comparator' => ComparatorTypeConst::CONST_GREATER_THAN
            ]
        ,
        'primary_key' => [ //設定主鍵。
            ['PK0', 123],
            ['PK1', 'abc']
        ],
        'attribute_columns' => $attr
    ];
    $response = $otsClient->putRow ($request);           

更新單行資料

調用UpdateRow介面更新一行資料,可以增加和刪除一行中的屬性列,刪除屬性列指定版本的資料,或者更新已存在的屬性列的值。如果更新的行不存在,則新增一行資料。
说明 當UpdateRow請求中只包含刪除指定的列且該行不存在時,則該請求不會新增一行資料。

介面

/**
 * 更新一行資料。
 * @api
 * @param [] $request 請求參數。
 * @return [] 請求返回。
 * @throws OTSClientException 當參數檢查出錯或服務端返回校正出錯時拋出異常。
 * @throws OTSServerException 當OTS服務端返回錯誤時拋出異常。
 */
public function updateRow(array $request);            

請求參數

參數 說明
table_name 資料表名稱。
condition 使用條件更新,可以設定原行的存在性條件或者原行中某列的列值條件。更多資訊,請參見條件更新
primary_key 行的主鍵。
说明 設定的主鍵個數和類型必須和資料表的主鍵個數和類型一致。
update_of_attribute_columns 更新的屬性列。
  • 增加或更新資料時,需要設定屬性名稱、屬性值、屬性類型(可選)、時間戳記(可選)。

    時間戳記即資料的版本號碼,可以由系統自動產生或者自訂,如果不設定此參數,則預設由系統自動產生。更多資訊,請參見資料版本和生命週期

    • 當由系統自動產生資料的版本號碼時,系統預設將目前時間的毫秒單位時間戳記(從1970-01-01 00:00:00 UTC計算起的毫秒數)作為資料的版本號碼。
    • 當自訂資料的版本號碼時,版本號碼需要為64位的毫秒單位時間戳記且在有效版本範圍內。
  • 刪除屬性列特定版本的資料時,只需要設定屬性名稱和時間戳記。

    時間戳記是64位整數,單位為毫秒,表示某個特定版本的資料。

  • 刪除屬性列時,只需要設定屬性名稱。
    说明 刪除一行的全部屬性列不等同於刪除該行,如果需要刪除該行,請使用DeleteRow操作。
return_content 表示傳回型別。

return_type:目前只需要設定為ReturnTypeConst::CONST_PK,表示返回主索引值,主要用於主鍵列自增情境。

請求格式

$result = $client->updateRow([
    'table_name' => '<string>', //設定資料表名稱。
    'condition' => [
        'row_existence' => <RowExistence>,
        'column_condition' => <ColumnCondition>
    ],
    'primary_key' => [                         //設定主鍵。
        ['<string>', <PrimaryKeyValue>], 
        ['<string>', <PrimaryKeyValue>],
        ['<string>', <PrimaryKeyValue>, <PrimaryKeyType>]
    ], 
    'update_of_attribute_columns' => [         //設定更新的屬性列。
        'PUT' => [
            ['<string>', <ColumnValue>], 
            ['<string>', <ColumnValue>, <ColumnType>],
            ['<string>', <ColumnValue>, <ColumnType>, <integer>]
        ],
        'DELETE' => [
            ['<string>', <integer>], 
            ['<string>', <integer>], 
            ['<string>', <integer>], 
            ['<string>', <integer>]
        ],
        'DELETE_ALL' => [
            '<string>',
            '<string>',
            '<string>',
            '<string>'
        ],        
    ],
    'return_content' => [
        'return_type' => <ReturnType>
    ]
]);            

響應參數

參數 說明
consumed 本次操作消耗服務能力單元的值。
capacity_unit表示使用的讀寫能力單元。
  • read:讀輸送量
  • write:寫輸送量
primary_key 主鍵的值,和請求時一致。
说明 當在請求中設定return_type為ReturnTypeConst::CONST_PK時,會返回完整的主鍵,主要用於主鍵列自增。
attribute_columns 屬性列的值,和請求時一致,目前為空白。

結果格式

[
    'consumed' => [
        'capacity_unit' => [
            'read' => <integer>,
            'write' => <integer>
        ]
    ],
    'primary_key' => [ 
        ['<string>', <PrimaryKeyValue>], 
        ['<string>', <PrimaryKeyValue>],
        ['<string>', <PrimaryKeyValue>, <PrimaryKeyType>]
    ],  
    'attribute_columns' => []
]            

樣本

  • 樣本1

    更新一些列,刪除某列的某一版本,刪除某列。

    $request = [
        'table_name' => 'MyTable',
        'condition' => RowExistenceExpectationConst::CONST_IGNORE,
        'primary_key' => [ //設定主鍵。
            ['PK0', 123],
            ['PK1', 'abc']
        ],
        'update_of_attribute_columns' => [
            'PUT' => [                       //更新一些列。
                ['Col0', 100],
                ['Col1', 'Hello'],
                ['Col2', 'a binary', ColumnTypeConst::CONST_BINARY],
                ['Col3', 100, null, 1526418378526]
            ],
            'DELETE' => [                    //刪除某列的某一版本。
                ['Col10', 1526418378526]
            ],
            'DELETE_ALL' => [
                'Col11'                      //刪除某一列。
            ]
        ]
    ];
    $response = $otsClient->updateRow($request);            
  • 樣本2

    設定更新的條件。

    $request = [
        'table_name' => 'MyTable',
        'primary_key' => [ //設定主鍵。
            ['PK0', 123],
            ['PK1', 'abc']
        ],
        'condition' => [
            'row_existence' => RowExistenceExpectationConst::CONST_EXPECT_EXIST, //期望原行存在。
            'column_filter' => [                                                 //當Col0列的值大於100時更新資料。
                'column_name' => 'Col0',
                'value' => 100,
                'comparator' => ComparatorTypeConst::CONST_GREATER_THAN
            ]
        ],    
        'update_of_attribute_columns' => [
            'PUT' => [                       //更新一些列。
                ['Col0', 100],
                ['Col1', 'Hello'],
                ['Col2', 'a binary', ColumnTypeConst::CONST_BINARY],
                ['Col3', 100, null, 1526418378526]
            ],
            'DELETE' => [                    //刪除某列的某一版本。
                ['Col10', 1526418378526]
            ],
            'DELETE_ALL' => [
                'Col11'                      //刪除某一列。
            ]
        ]
    ];         

批量寫入資料

調用BatchWriteRow介面在一次請求中進行批量的寫入操作,也支援一次對多張表進行寫入。BatchWriteRow操作由多個PutRow、UpdateRow、DeleteRow子操作組成,構造子操作的過程與使用PutRow介面、UpdateRow介面和DeleteRow介面時相同,也支援使用條件更新。

BatchWriteRow的各個子操作獨立執行,Tablestore會分別返回各個子操作的執行結果。

注意事項

由於批量寫入可能存在部分行失敗的情況,失敗行的Index及錯誤資訊在返回的BatchWriteRowResponse中,但並不拋出異常。因此調用BatchWriteRow介面時,需要檢查傳回值,判斷每行的狀態是否成功;如果不檢查傳回值,則可能會忽略掉部分操作的失敗。

當服務端檢查到某些操作出現參數錯誤時,BatchWriteRow介面可能會拋出參數錯誤的異常,此時該請求中所有的操作都未執行。

介面

/**
 * 寫入、更新或者刪除指定的多行資料。
 * 請注意BatchWriteRow在部分行讀取失敗時,會在返回的$response中表示,而不是拋出異常。更多資訊,請參見處理BatchWriteRow的返回範例。
 * @api
 * @param [] $request 請求參數。
 * @return [] 請求返回。
 * @throws OTSClientException 當參數檢查出錯或服務端返回校正出錯時。
 * @throws OTSServerException 當OTS服務端返回錯誤時。
 */
public function batchWriteRow(array $request);              

請求參數

本操作是PutRow、UpdateRow、DeleteRow的組合。
  • 增加了資料表的層級結構,可以一次處理多個資料表。

    tables以資料表為單位組織,後續為各個資料表的操作,設定需要寫入、修改或刪除的行資訊。

  • 增加了operation_type參數,用於區分操作類型。
    操作類型可以為PUT、UPDATE、DELETE,分別用OperationTypeConst::CONST_PUT、OperationTypeConst::CONST_UPDATE、OperationTypeConst::CONST_DELETE表示。
    • 當操作類型為PUT時,primary_key和attribute_columns有效。
    • 當操作類型為UPDATE時,primary_key和update_of_attribute_columns有效。
    • 當操作類型為DELETE時,primary_key有效。

請求格式

$result = $client->batchWriteRow([
    'tables' => [                                            //設定資料表的層級結構。
        [
            'table_name' => '<string>',                      //設定資料表名稱。
            'operation_type' => <OperationType>,
            'condition' => [
                'row_existence' => <RowExistence>,   
                'column_condition' => <ColumnCondition>
            ],
            'primary_key' => [                               //設定主鍵。
                ['<string>', <PrimaryKeyValue>], 
                ['<string>', <PrimaryKeyValue>],
                ['<string>', <PrimaryKeyValue>, <PrimaryKeyType>]
            ], 
            'attribute_columns' => [                        //當操作類型為PUT時必須設定。
                    ['<string>', <ColumnValue>], 
                    ['<string>', <ColumnValue>, <ColumnType>],
                    ['<string>', <ColumnValue>, <ColumnType>, <integer>]
            ],
            'update_of_attribute_columns' => [               //當操作類型為UPDATE時必須設定。
                'PUT' => [
                    ['<string>', <ColumnValue>], 
                    ['<string>', <ColumnValue>, <ColumnType>],
                    ['<string>', <ColumnValue>, <ColumnType>, <integer>]
                ],
                'DELETE' => [
                    ['<string>', <integer>], 
                    ['<string>', <integer>], 
                    ['<string>', <integer>], 
                    ['<string>', <integer>]
                ],
                'DELETE_ALL' => [
                    '<string>',
                    '<string>',
                    '<string>',
                    '<string>'
                ],
            ],
            'return_content' => [
                'return_type' => <ReturnType>
            ]
        ],
        //其他資料表。
    ]
]);        

響應參數

tables以table為單位組織,和請求一一對應,參數說明請參見下表。
參數 說明
table_name 資料表名稱。
is_ok 該行操作是否成功。
  • 如果值為true,則該行寫入成功,此時error無效。
  • 如果值為false,則該行寫入失敗。
error 用於在操作失敗時的響應訊息中表示錯誤資訊。
  • code表示當前單行操作的錯誤碼。
  • message表示當前單行操作的錯誤資訊。
consumed 本次操作消耗服務能力單元的值。
capacity_unit表示使用的讀寫單元。
  • read:讀輸送量
  • write:寫輸送量
primary_key 主鍵的值,和請求時一致。

設定return_type時會有值,主要用於主鍵列自增。

attribute_columns 屬性列的值,和請求時一致,目前為空白。

結果格式

[
    'tables' => [
        [
            'table_name' => '<string>',
            'rows' => [
                [
                    'is_ok' => true || false,
                    'error' => [
                        'code' => '<string>',
                        'message' => '<string>',
                    ]
                    'consumed' => [
                        'capacity_unit' => [
                            'read' => <integer>,
                            'write' => <integer>
                        ]
                    ],
                    'primary_key' => [ 
                        ['<string>', <PrimaryKeyValue>], 
                        ['<string>', <PrimaryKeyValue>],
                        ['<string>', <PrimaryKeyValue>, <PrimaryKeyType>]
                    ],
                    'attribute_columns' => []
                ],
                //其他行。
            ]
        ],
        //其他資料表。
    ]
]           

樣本

批量寫入30行資料,分別向3個資料表中寫入資料,每個資料表中寫入10行。

//向3個資料表中寫入資料,每個資料表中寫入10行。
$tables = array();
for($i = 0; $i < 3; $i++) {
    $rows = array();
    for($j = 0; $j < 10; $j++) {
        $rows[] = [
            'operation_type' => OperationTypeConst::CONST_PUT, //設定作業類型為PUT。
            'condition' => RowExistenceExpectationConst::CONST_IGNORE,
            'primary_key' => [
                ['pk0', $i],
                ['pk1', $j]
            ],
            'attribute_columns' => [
                ['Col0', 4],
                ['Col2', '成杭京']
            ]
        ];
    }
    $tables[] = [
        'table_name' => 'SampleTable' . $i,
        'rows' => $rows
    ];
}
$request = [
    'tables' => $tables
];
$response = $otsClient->batchWriteRow ($request);
//處理返回的每個資料表。
foreach ($response['tables'] as $tableData) {
  print "Handling table {$tableData['table_name']} ...\n";

  //處理該資料表下的PutRow返回的結果。
  $putRows = $tableData['rows'];

  foreach ($putRows as $rowData) {

    if ($rowData['is_ok']) {
      //寫入成功。
      print "Capacity Unit Consumed: {$rowData['consumed']['capacity_unit']['write']}\n";
    } else {

      //處理出錯。
      print "Error: {$rowData['error']['code']} {$rowData['error']['message']}\n";
    }
  }
}           

詳細程式碼範例請參見下表。

樣本 說明
BatchWriteRow1.php 展示了BatchWriteRow中多個PUT的用法。
BatchWriteRow2.php 展示了BatchWriteRow中多個UPDATE的用法。
BatchWriteRow3.php 展示了BatchWriteRow中多個DELETE的用法。
BatchWriteRow4.php 展示了BatchWriteRow中組合使用UPDATE、PUT和DELETE的用法。
BatchWriteRowWithColumnFilter.php 展示了BatchWriteRow中同時使用條件更新的用法。