本文介紹如何通過 Node.js SDK 對錶格儲存的資料進行批次更新操作,包括寫入資料、修改資料和刪除資料,支援同時操作多個表的資料。
注意事項
服務端檢查到部分操作的參數錯誤時會拋出參數錯誤異常,此時該請求中的所有操作都將不執行。
批次更新操作單次支援寫入的最大行數為200行,且所有行的資料量總和不能超過4MB。
前提條件
方法說明
batchWriteRow: function batchWriteRow(params, callback)範例程式碼
以下範例程式碼使用批量資料操作方法在 test_table 表中插入一行資料。
var table = {
tableName: 'test_table',
rows: [
{
type: 'PUT',
// 寫入資料時必須指定寫入條件 (TableStore.RowExistenceExpectation.IGNORE,表示不做行存在性判斷)
condition: new TableStore.Condition(TableStore.RowExistenceExpectation.IGNORE, null),
primaryKey: [{ 'id': 'row1' }]
}
]
};
var params = {
tables: [table]
};
// 調用 batchWriteRow 方法進行批量資料查詢
client.batchWriteRow(params, function (err, data) {
if (err) {
console.log('Batch write row failed with error: %s', err);
return;
}
// 返回結果處理
console.log('RequestId: %s', data.RequestId);
data.tables.forEach(function (item) {
if (!item.isOk) {
console.log('Table name: %s. Error message: %s', item.tableName, item.errorMessage);
}
});
});不同類型的資料操作範例程式碼參考如下。
PutRowChange:寫入行資料。
var table = { tableName: 'test_table', rows: [ { type: 'PUT', // 寫入資料時必須指定寫入條件 (TableStore.RowExistenceExpectation.IGNORE,表示不做行存在性判斷) condition: new TableStore.Condition(TableStore.RowExistenceExpectation.IGNORE, null), primaryKey: [{ 'id': 'row1' }] } ] };寫入行資料時添加屬性列。
var table = { tableName: 'test_table', rows: [ { type: 'PUT', // 寫入資料時必須指定寫入條件 (TableStore.RowExistenceExpectation.IGNORE,表示不做行存在性判斷) condition: new TableStore.Condition(TableStore.RowExistenceExpectation.IGNORE, null), primaryKey: [{ 'id': 'row1' }], attributeColumns: [ // 添加屬性列 { 'col1': 'val1' }, // 添加自訂資料版本號碼的屬性列 { 'col2': 'val2', 'timestamp': Date.now() } ] } ] };UpdateRowChange:更新行資料,您可以修改屬性列的值、添加資料列、刪除屬性列的某個版本或整個屬性列。
var table = { tableName: 'test_table', rows: [ { type: 'UPDATE', // 更新資料時必須指定更新條件 (TableStore.RowExistenceExpectation.IGNORE,表示不做行存在性判斷) condition: new TableStore.Condition(TableStore.RowExistenceExpectation.IGNORE, null), primaryKey: [{ 'id': 'row1' }], attributeColumns: [{ 'PUT': [{ 'col1': 'changed_val1' }] }], } ] };更新行資料時添加或刪除屬性列。
var table = { tableName: 'test_table', rows: [ { type: 'UPDATE', // 更新資料時必須指定更新條件 (TableStore.RowExistenceExpectation.IGNORE,表示不做行存在性判斷) condition: new TableStore.Condition(TableStore.RowExistenceExpectation.IGNORE, null), primaryKey: [{ 'id': 'row1' }], attributeColumns: [ { 'PUT': [ // 添加屬性列 { 'col3': 'val3' }, // 添加自訂資料版本號碼的屬性列 { 'col4': 'val4', 'timestamp': Date.now() } ] }, { // 刪除屬性列 'DELETE_ALL': ['col2'] } ], } ] };DeleteRowChange:刪除行資料。
var table = { tableName: 'test_table', rows: [ { type: 'DELETE', // 刪除行資料時必須指定刪除條件 (TableStore.RowExistenceExpectation.IGNORE,表示不做行存在性判斷) condition: new TableStore.Condition(TableStore.RowExistenceExpectation.IGNORE, null), primaryKey: [{ 'id': 'row1' }] } ] };