有条件的 Azure Cosmos DB for Apache Cassandra 轻型事务

适用对象: Cassandra

与大多数 NoSQL 数据库平台一样,Apache Cassandra 优先考虑可用性和分区容错能力而不是一致性,因为它不像关系数据库那样能够支持 ACID 事务。 如需详细了解一致性级别如何适用于 LWT,请参阅 一致性级别。 Cassandra 支持轻型事务 (LWT),这近似于 ACID。 它有助于在写入前执行读取,因为需要数据插入或更新的操作必须是唯一的。

Azure Cosmos DB for Apache Cassandra 中的 LWT 支持

若要在 AAzure Cosmos DB for Apache Cassandra 内使用 LWT,建议在创建表级别设置以下标志。

with cosmosdb_cell_level_timestamp=true and cosmosdb_cell_level_timestamp_tombstones=true and cosmosdb_cell_level_timetolive=true

与不使用标志相比,在整行插入时你可能会遇到性能下降的问题。

备注

多区域写入场景不支持 LWT。

已启用标志的 LWT

CREATE KEYSPACE IF NOT EXISTS lwttesting WITH REPLICATION= {'class': 'org.apache.cassandra.locator.SimpleStrategy', 'replication_factor' : '1'};
CREATE TABLE IF NOT EXISTS lwttesting.users (
  name text,
  userID int,
  address text,
  phoneCode int,
  vendorName text STATIC,
  PRIMARY KEY ((name), userID)) with cosmosdb_cell_level_timestamp=true and cosmosdb_cell_level_timestamp_tombstones=true and cosmosdb_cell_level_timetolive=true; 

下面的查询返回 TRUE。

INSERT INTO lwttesting.users(name, userID, phoneCode, vendorName)
VALUES('Sara', 103, 832, 'vendor21') IF NOT EXISTS; 

限制

启用的标志存在一些已知限制。

  • 如果已将某行插入表中,则尝试插入静态行会返回 FALSE。

    INSERT INTO lwttesting.users (userID, vendorName)
    VALUES (104, 'staticVendor') IF NOT EXISTS;
    

    上述查询当前返回 FALSE,但应为 TRUE。

  • 尝试在 TTL 过期后插入另一行,返回 false。

    CREATE TABLE IF NOT EXISTS lwttesting.customers (
      customer text PRIMARY KEY, 
      user text, entry timestamp) with cosmosdb_cell_level_timestamp=true and cosmosdb_cell_level_timestamp_tombstones=true and cosmosdb_cell_level_timetolive=true;
    
    INSERT INTO lwttesting.customers (customer, user, entry) 
    VALUES ('vendor', 'Sara', '2023-10-10 15:00:00.000000+0000') IF NOT EXISTS USING TTL 30;
    

    此查询返回 TRUE。 但是,尝试另一个插入会返回 FALSE。

标志已禁用的 LWT

如果未启用标志,那么不支持与 IF 条件结合使用的行删除。

CREATE TABLE IF NOT EXISTS lwttesting.vendor_users (
  name text,
  userID int,
  areaCode int,
  vendor text STATIC,
  PRIMARY KEY ((userID), name)
);
DELETE FROM lwttesting.vendor_users 
WHERE userID =103 AND name = 'Sara' 
IF areaCode = 832;

错误消息:不支持对整行进行条件删除。

标志启用或禁用的 LWT

IF 条件不支持包含分配以及静态和常规列的条件结合的任何请求。 此查询不会返回错误消息,因为两列都是常规的。

DELETE areaCode 
FROM lwttesting.vendor_users 
WHERE name= 'Sara' 
AND userID = 103 IF areaCode = 832;   

但是,下面的查询将返回一条错误消息 Conditions and assignments containing combination of Static and Regular columns are not supported.

DELETE areaCode 
FROM lwttesting.vendor_users 
WHERE name= 'Sara' AND userID = 103 IF vendor = 'vendor21';  

后续步骤

在本教程中,你已了解轻型事务在 Azure Cosmos DB for Apache Cassandra 中的工作原理。 可以继续阅读下一篇文章: