在一个查询中更新多个计数器

Updating multiple counters in one query

我的应用程序当前执行类似以下操作(最小示例):

UPDATE counts SET count = count + 1 WHERE id = 1
UPDATE counts SET count = count + 1 WHERE id = 2
UPDATE counts SET count = count + 1 WHERE id = 2
UPDATE counts SET count = count + 1 WHERE id = 3
UPDATE counts SET count = count + 1 WHERE id = 3

但是每秒有几千次更新,在高峰流量时它太慢了。

所以我想通过合并语句来加快速度。以下当然不起作用:

UPDATE counts SET count = count + 1 WHERE id IN (1, 2, 2, 3, 3)

23count 是错误的(1 而不是 2)。

我是否必须手动将其拆分为如下内容:

UPDATE counts SET count = count + 1 WHERE id IN (1, 2, 3)
UPDATE counts SET count = count + 1 WHERE id IN (2, 3)

或者直接在语句中有更聪明的方法吗?

您可以使用除 1 之外的其他数字来添加计数。 (在功能上,你可以;你必须测试性能。)

cqlsh> UPDATE mykeyspace.counts SET count = count + 1 where k1=1;
cqlsh> UPDATE mykeyspace.counts SET count = count + 1 where k1=2;
cqlsh> UPDATE mykeyspace.counts SET count = count + 1 where k1=3;
cqlsh> select * from mykeyspace.counts ;

 k1 | count
----+-------
  1 |     1
  2 |     1
  3 |     1

(3 rows)
cqlsh> UPDATE mykeyspace.counts SET count = count + 57 where k1=1;
cqlsh> select * from mykeyspace.counts ;

 k1 | count
----+-------
  1 |    58
  2 |     1
  3 |     1

(3 rows)
cqlsh> UPDATE mykeyspace.counts SET count = count + 65 where k1 in (2,3);
cqlsh> select * from mykeyspace.counts ;

 k1 | count
----+-------
  1 |    58
  2 |    66
  3 |    66