I have a table 'reviews' in Cassandra as mentioned below:
CREATE TABLE reviews (
review_id text,
downcount int,
upcount int,
creation_date timestamp,
PRIMARY KEY (review_id)
)
Lets say I want to increase the upcount
value by 1, how can I do that in Cassandra CQL?
When I do:
UPDATE reviews SET upcount = upcount +1 WHERE review_id = '123456';
It gives me the below error:
Bad Request: Invalid operation (
upcount = upcount + 1
) for non counter columnupcount
.
UPDATE writes one or more column values to a row in a Cassandra table. Like INSERT, UPDATE is an upsert operation: if the specified row does not exist, the command creates it. All UPDATEs within the same partition key are applied atomically and in isolation.
In Cassandra, to modify a column by executing an ALTER statement. Using ALTER table statement You can change the type of a column, Add a new column, Drop a column, Rename existing column as shown here: ALTER TABLE [keyspace_name.]
Specify other column values using SET. To update multiple columns, separate the name-value pairs using commas.
Cassandra treats each new row as an upsert: if the new row has the same primary key as that of an existing row, Cassandra processes it as an update to the existing row. During a write, Cassandra adds each new row to the database without checking on whether a duplicate record exists.
You can use Cassandra's counter columns data type. Keep in mind you cannot mix counter columns with non-counter columns in the same column family if the non-counter columns are not part of the composite PRIMARY KEY
. So you have to separate the counters into another column family, say reviews_counts
.
CREATE TABLE reviews (
review_id text,
creation_date timestamp,
PRIMARY KEY (review_id)
)
CREATE TABLE reviews_counts (
review_id text,
downcount counter,
upcount counter,
PRIMARY KEY (review_id)
)
Now the increment statement should work.
UPDATE keyspace.reviews_counts
SET upcount = upcount + 1
WHERE review_id = '123456'
Here is some more documentation about Cassandra counter columns. http://www.datastax.com/documentation/cql/3.0/cql/cql_using/use_counter_t.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With