cassandra-如何通过添加到现有值来更新小数列 [英] cassandra - how to update decimal column by adding to existing value
问题描述
我有一个如下所示的cassandra表:
I have a cassandra table that looks like the following:
create table position_snapshots_by_security(
securityCode text,
portfolioId int,
lastUpdated date,
units decimal,
primary key((securityCode), portfolioId)
)
我想要这样的东西:
update position_snapshots_by_security
set units = units + 12.3,
lastUpdated = '2017-03-02'
where securityCode = 'SPY'
and portfolioId = '5dfxa2561db9'
但这是行不通的.
是否可以在Cassandra中执行这种操作?我使用的是最新版本3.10.
Is it possible to do this kind of operation in Cassandra? I am using version 3.10, the latest one.
谢谢!
J
推荐答案
Cassandra doesn't do a read before a write (except when using Lightweight Transactions) so it doesn't support operations like the one you're trying to do which rely on the existing value of a column. With that said, it's still possible to do this in your application code with Cassandra. If you'll have multiple writers possibly updating this value, you'll want to use the aforementioned LWT to make sure the value is accurate and multiple writers don't "step on" each other. Basically, the steps you'll want to follow to do that are:
- 使用
SELECT
从Cassandra读取当前值.如果您使用的是LWT,请确保以SERIAL
或LOCAL_SERIAL
的一致性级别进行读取. - 进行计算以将其添加到应用程序代码中的当前值.
- 使用
UPDATE
语句更新Cassandra中的值.如果使用LWT,则需要进行UPDATE ... IF value = previous_value_you_read
.
- Read the current value from Cassandra using a
SELECT
. Make sure you're doing the read with a consistency level ofSERIAL
orLOCAL_SERIAL
if you're using LWTs. - Do the calculation to add to the current value in your application code.
- Update the value in Cassandra with an
UPDATE
statement. If using a LWT you'll want to doUPDATE ... IF value = previous_value_you_read
.
如果使用LWT,则在执行计算时,如果读取的先前值发生更改,则将拒绝 UPDATE
.(并且您可以重试整个步骤.)请记住,LWT是昂贵的操作,尤其是在您正在读取/更新的键存在激烈竞争的情况下.
If using LWTs, the UPDATE
will be rejected if the previous value that you read changed while you were doing the calculation. (And you can retry the whole series of steps again.) Keep in mind that LWTs are expensive operations, particularly if the keys you are reading/updating are heavily contended.
希望有帮助!
这篇关于cassandra-如何通过添加到现有值来更新小数列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!