本文介紹如何通過 PHP SDK 對錶格儲存的資料進行批次更新操作,包括寫入資料、修改資料和刪除資料,支援同時操作多個表的資料。
注意事項
服務端檢查到部分操作的參數錯誤時會拋出參數錯誤異常,此時該請求中的所有操作都將不執行。
批次更新操作單次支援寫入的最大行數為200行,且所有行的資料量總和不能超過4MB。
前提條件
方法說明
public function batchWriteRow(array $request)範例程式碼
以下範例程式碼使用批量資料操作方法在 test_table 表中插入一行資料。
$table = array (
'table_name' => 'test_table',
'rows' => array (
array (
'operation_type' => OperationTypeConst::CONST_PUT,
'primary_key' => array ( array('id', 'row1') )
)
)
);
$request = array(
'tables' => array (
$table
)
);
try {
// 調用 batchWriteRow 方法進行批量資料操作
$response = $client->batchWriteRow ($request);
// 返回結果處理
foreach ($response['tables'] as $tableGroup) {
foreach ($tableGroup['rows'] as $row) {
if (!$row['is_ok']) {
echo "TableName: {$tableGroup['table_name']}. ErrorCode: {$row['error']['code']}. ErrorMessage: {$row['error']['message']} \n";
}
}
}
} catch (Exception $e){
echo 'Batch write row failed.';
}不同類型的資料操作範例程式碼參考如下。
PutRowItem:寫入行資料。
$table = array ( 'table_name' => 'test_table', 'rows' => array ( array ( 'operation_type' => OperationTypeConst::CONST_PUT, 'primary_key' => array ( array('id', 'row1') ) ) ) );寫入行資料時添加屬性列。
$table = array ( 'table_name' => 'test_table', 'rows' => array ( array ( 'operation_type' => OperationTypeConst::CONST_PUT, 'primary_key' => array ( array('id', 'row1') ), 'attribute_columns' => array ( array('col1', 'val1'), array('col2', 'val2', null, intval(microtime(true) * 1000)) ) ) ) );UpdateRowItem:更新行資料,您可以修改屬性列的值、添加資料列、刪除屬性列的某個版本或整個屬性列。
$table = array ( 'table_name' => 'test_table', 'rows' => array ( array ( 'operation_type' => OperationTypeConst::CONST_UPDATE, 'primary_key' => array ( array('id', 'row1') ), 'update_of_attribute_columns'=> array( 'PUT' => array ( array('col1', 'changed_val1') ) ), // 更新行資料時必須指定更新條件 (RowExistenceExpectation.IGNORE,表示不做行存在性判斷) 'condition' => RowExistenceExpectationConst::CONST_IGNORE ) ) );更新行資料時添加或刪除屬性列。
$table = array ( 'table_name' => 'test_table', 'rows' => array ( array ( 'operation_type' => OperationTypeConst::CONST_UPDATE, 'primary_key' => array ( array('id', 'row1') ), 'update_of_attribute_columns'=> array( 'PUT' => array ( // 添加屬性列 array('col3', 'val3'), // 添加自訂資料版本號碼的屬性列 array('col4', 'val4', null, intval(microtime(true) * 1000)) ), // 刪除屬性列 'DELETE_ALL' => array('col2') ), // 更新行資料時必須指定更新條件 (RowExistenceExpectation.IGNORE,表示不做行存在性判斷) 'condition' => RowExistenceExpectationConst::CONST_IGNORE ) ) );DeleteRowItem:刪除行資料。
$table = array ( 'table_name' => 'test_table', 'rows' => array ( array ( 'operation_type' => OperationTypeConst::CONST_DELETE, 'primary_key' => array ( array('id', 'row1') ), // 刪除行資料時必須指定刪除條件 (RowExistenceExpectation.IGNORE,表示不做行存在性判斷) 'condition' => RowExistenceExpectationConst::CONST_IGNORE ) ) );