问题
I have a cassandra table1:
CREATE TABLE Policy.table1 (
name VARCHAR ,
date TIMESTAMP ,
version_num INT,
PRIMARY KEY (
name
)) WITH caching = 'all'
-- and memtable_flush_period_in_ms = 7200 ;
;
I need to implement optimistic locking on tis table. When we read a row from table1 we remember its version_num. And when we want to update this row we compare current version_num value and value that we remembered. Also we need to increment version_num on each update.
Problems:
We cannot put version_num into where clause, this will create an error: Bad Request: Non PRIMARY KEY version_num found in where clause:
update table where name = 'abc' and version = 3
We cannot set version_num as a part of primary key, because we need to update its value
- If we index version_num it will not help for update statements, same exception will be thrown
- The only way I see is to get current version_num value by Java, and if expected and actual version_num values are the same - than execute update. The problem is that in this case we have not atomic operation of checking version_num value and update the row.
Do you see any solution for this problem?
回答1:
The solution was found there: Cassandra 2.0, Lightweight transactions http://www.datastax.com/documentation/cassandra/2.0/cassandra/dml/dml_ltwt_transaction_c.html
In case I execute query:
update table1 set version_num = 5 where name = 'abc' if version_num = 4;
I will receive a row with [applied]
column. This row contains boolean value: true
= update was successful, false
= in other case.
来源:https://stackoverflow.com/questions/24406252/cassandra-optimistic-locking