条件更新是指只有在满足条件时才对表中的数据进行更改,当不满足条件时更新失败。条件更新可用于put_row、update_row、delete_row和batch_write_row等操作。
参数说明
条件更新的判断条件包括行存在性条件和列条件。
- 行存在性条件包含:
- IGNORE:忽略
- EXPECT_EXIST:期望存在
- EXPECT_NOT_EXIST:期望不存在
说明 在对表进行更改操作时,会首先检查行存在性条件。若不满足行存在性条件,则更改失败,出现报错。 - 列条件基于某一列或者某些列的列值进行条件判断,与过滤器中的条件类似。列条件包含:
- SingleColumnCondition:单列条件
- CompositeColumnCondition:组合列条件
基于条件更新可以实现乐观锁的功能,即在更新某行时,先获取某列的值。假设为列 A,值为 1,然后设置条件“列 A=1”,更新该行同时使“列 A=2”。若更新失败,代表有其他客户端已经成功更新了该行。
示例
// 定义行的主键,必须与创建表时的TableMeta中定义的一致
PrimaryKey primaryKey = new PrimaryKey();
primaryKey.Add("pk0", new ColumnValue(0));
primaryKey.Add("pk1", new ColumnValue("abc"));
// 定义要写入改行的属性列
AttributeColumns attribute = new AttributeColumns();
attribute.Add("col0", new ColumnValue(0));
attribute.Add("col1", new ColumnValue("a"));
attribute.Add("col2", new ColumnValue(true));
PutRowRequest request = new PutRowRequest(tableName, new Condition(RowExistenceExpectation.IGNORE), primaryKey, attribute);
// 不带condition时putrow,预期成功
try
{
otsClient.PutRow(request);
Console.WriteLine("Put row succeeded.");
} catch (Exception ex)
{
Console.WriteLine("Put row failed. error:{0}", ex.Message);
}
// 当col0列的值不等于5,允许再次putrow,覆盖掉原值,预期成功
try
{
request.Condition.ColumnCondition = new RelationalCondition("col0",
CompareOperator.NOT_EQUAL,
new ColumnValue(5));
otsClient.PutRow(request);
Console.WriteLine("Put row succeeded.");
} catch (Exception ex)
{
Console.WriteLine("Put row failed. error:{0}", ex.Message);
}
// 当col0列的值等于5,允许再次putrow,覆盖掉原值,预期失败
try
{
// 新增条件:col0列的值等于5
request.Condition.ColumnCondition = new RelationalCondition("col0",
CompareOperator.EQUAL,
new ColumnValue(5));
otsClient.PutRow(request);
Console.WriteLine("Put row succeeded.");
}
catch (OTSServerException)
{
// 由于条件不满足,抛出OTSServerException
Console.WriteLine("Put row failed because condition check failed. but expected");
}
catch (Exception ex)
{
Console.WriteLine("Put row failed. error:{0}", ex.Message);
}
在文档使用中是否遇到以下问题
更多建议
匿名提交