条件更新

更新时间:
复制 MD 格式

本文介绍如何在 Node.js SDK 中使用条件更新,设置更新条件后,只有目标行数据满足指定的条件,才能完成更新。

前提条件

初始化Tablestore Client

功能说明

条件更新的构造函数定义如下:

TableStore.Condition = inherit({
    constructor: function (rowExistenceExpectation, columnCondition)
    
    // other method
});

参数说明

  • rowExistenceExpectation(必选)TableStore.RowExistenceExpectation:行存在性条件,包括以下三种类型。

    • IGNORE:不做行存在性判断。

    • EXPECT_EXIST:数据表中存在目标行数据时满足条件,否则不满足。

    • EXPECT_NOT_EXIST:数据表中不存在目标行数据时满足条件,否则不满足。

  • columnCondition(可选)TableStore.ColumnCondition:列值判断条件,包括以下两种类型。

    • TableStore.SingleColumnCondition:判断单个属性列的值是否满足条件。参数说明如下:

      名称

      类型

      说明

      comparator(必选)

      TableStore.ComparatorType

      关系运算符,包括 EQUAL(等于)、NOT_EQUAL(不等于)、GREATER_THAN(大于)、GREATER_EQUAL(大于等于)、LESS_THAN(小于)、LESS_EQUAL(小于等于)。

      columnName(必选)

      string

      判断的属性列名称。

      columnValue(必选)

      STRING,INTEGER,BINARY,DOUBLE,BOOLEAN

      判断的值。

      passIfMissing(可选)

      boolean

      行数据不包含目标属性列时,是否满足条件,默认值为 true,即行数据不包含目标属性列时满足条件,否则不满足。

      latestVersionOnly(可选)

      boolean

      是否只判断最新的数据版本,默认值为 true,即当目标属性列存在多个数据版本时,只判断最新的数据版本是否符合判断条件;如果为 false,则任一数据版本符合即视为满足条件。

    • TableStore.CompositeCondition:判断行数据是否满足组合判断条件。参数说明如下:

      名称

      类型

      说明

      combinator(必选)

      TableStore.LogicalOperator

      逻辑运算符,包括 NOT(非)、AND(与)、OR(或)。

      sub_conditions(必选)

      Array

      参与逻辑运算的子条件列表。

      • 子条件可以是 TableStore.SingleColumnCondition 或 TableStore.CompositeCondition。

      • 最多支持 32 个条件的组合。

示例代码

以下示例代码以 updateRow 方法为例介绍如何设置条件更新。

var params = {
    tableName: 'test_condition',
    primaryKey: [{ 'id': 'row1' }],
    updateOfAttributeColumns: [
        { 'PUT': [{ 'col1': 'changed_val1' }] }
    ]
};
// 构造更新条件(目标行数据在数据表中存在时才进行数据更新)
params.condition = new TableStore.Condition(TableStore.RowExistenceExpectation.EXPECT_EXIST, null)

// 调用 updateRow 方法更新行数据
client.updateRow(params, function (err, data) {
    if (err) {
        console.log('Update row failed with error:', err);
        return;
    }
    
    // 返回结果处理
    console.log('RequestId:', data.RequestId);
    console.log('Read CU Cost:', data.consumed.capacityUnit.read);
    console.log('Write CU Cost:', data.consumed.capacityUnit.write);
});
  • 设置列值判断条件,判断单个属性列的值是否满足条件。

    // col1 列的值等于 val1 时才进行数据更新
    var singleColumnCondition = new TableStore.SingleColumnCondition('col1', 'val1', TableStore.ComparatorType.EQUAL)
    params.condition = new TableStore.Condition(TableStore.RowExistenceExpectation.EXPECT_EXIST, singleColumnCondition)
  • 设置列值判断条件,对多个条件进行判断。

    // 设置组合条件 1
    var compositeCondition1 = new TableStore.CompositeCondition(TableStore.LogicalOperator.AND);
    // 添加子条件
    compositeCondition1.addSubCondition(new TableStore.SingleColumnCondition('col1', 'val1', TableStore.ComparatorType.EQUAL));
    compositeCondition1.addSubCondition(new TableStore.SingleColumnCondition('col2', 'val2', TableStore.ComparatorType.EQUAL));
    // 设置组合条件 2
    var compositeCondition2 = new TableStore.CompositeCondition(TableStore.LogicalOperator.OR);
    compositeCondition2.addSubCondition(compositeCondition1);
    compositeCondition2.addSubCondition(new TableStore.SingleColumnCondition('col3', 'val3', TableStore.ComparatorType.EQUAL));
    // 添加组合条件,判断条件为(col1 = val1 and col2 = val2) or (col3 = val3)
    params.condition = new TableStore.Condition(TableStore.RowExistenceExpectation.EXPECT_EXIST, compositeCondition2)

场景案例

以下示例代码使用条件更新功能模拟乐观锁的 CAS 实现。

async function optimisticLocking() {
    try {
        // 读取原属性列的值
        const getRowParams = {
            tableName: 'test_condition',
            primaryKey: [{ 'id': 'row1' }],
            maxVersions: 1,
            // 指定读取的属性列
            columnsToGet: ['col1']
        };
        const getRowResponse = await client.getRow(getRowParams);
        const oldValue = getRowResponse.row.attributes[0].columnValue;

        // 更新数据
        const updateRowParams = {
            tableName: 'test_condition',
            primaryKey: [{ 'id': 'row1' }],
            updateOfAttributeColumns: [
                { 'PUT': [{ 'col1': 'changed_val1' }] }
            ]
        }
        // 构造更新条件,目标属性列最新版本的值等于预期值(读取到的值)时,才进行更新
        const singleColumnCondition = new TableStore.SingleColumnCondition('col1', oldValue, TableStore.ComparatorType.EQUAL, true, true);
        updateRowParams.condition = new TableStore.Condition(TableStore.RowExistenceExpectation.EXPECT_EXIST, singleColumnCondition);
        const updateRowResponse = await client.updateRow(updateRowParams);

        // 返回结果处理
        console.log('RequestId:', updateRowResponse.RequestId);
        console.log('Read CU Cost:', updateRowResponse.consumed.capacityUnit.read);
        console.log('Write CU Cost:', updateRowResponse.consumed.capacityUnit.write);
    } catch (err) {
        console.log('Failed with error: ', err);
    }
}

optimisticLocking()