Cassandra - 使计数器更新和正常更新原子化

Cassandra - Make Counter Update And Normal Update Atomic

我正在经历这个Instagram engineering article,他们在其中提到了反规范化计数器,我引用

To reduce the resources needed for each of these operations, we denormalized the counter for likes on the post. Whenever a new like comes in, the count is increased in the database. Therefore, each read of the count will just be a simple “select” which is a lot more efficient.

There is also an added benefit of denormalizing counters in the same database where the liker to the post is stored. Both updates can be included in one transaction, making the updates atomic and consistent all the time. Whereas before the change, the counter in cache could be inconsistent with what was stored in the database due to timeout, retries etc.

我尝试更新计数器 table 和一个正常的 table,其中有喜欢 post 的用户批量使用,

BEGIN BATCH 
  UPDATE postlike_counter_counter
    set likecount = likecount+1 
    where postid = c77b9e44-379b-11e7-93dc-dd4982fae088;
  INSERT INTO postlikes (postid, likedtime, likedby) values(c77b9e44-379b-11e7-93dc-dd4982fae088, unixTimestampOf(now()), 
    {"firstname": 'fname', "lastname": 'lname', "profileimgurl":'img/pic'});
APPLY BATCH;

我看到了错误,计数器突变只允许在 COUNTER 个批次中使用 如果我把它作为一个反批次,我得到,在反批次中只允许反突变

我有什么方法可以让它工作吗?如果不是,那么他们写上面引述的行时,这篇文章到底是什么意思?

计数器更新和普通更新不能在同一批次使用。

Counter batches cannot include non-counter columns in the DML statements, just as a non-counter batch cannot include counter columns. Counter batch statements cannot provide custom timestamps.

你必须使用单独的批次。

先申请counter batch,成功后再申请non counter batch。如果非计数器批处理失败,则切换计数器语句的符号(set a = a + 1 to a = a - 1 或反之亦然)并应用该批处理。

在 Java 中,您可以通过 wasApplied() 方法

检查批处理是否成功
ResultSet resultSet = session.execute(batch);

if(resultSet.wasApplied()) {
    // Batch success
}

来源:https://docs.datastax.com/en/cql/3.3/cql/cql_reference/cqlBatch.html

Ashraful Islam 已经回答了为什么 Cassandra 不允许在一个批次中混合计数器查询和非计数器查询的问题。但是你引用的上下文 并没有发生在 cassandra 世界中 Instagram engineering article (De-normalizing Counters) is trying to explaining in the PgQ 世界(在实际可能的情况下,它们也不是计数器数据类型,而是作为一种计数器维护)