Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you update a Cassandra integer column using CQL?

Tags:

cassandra

cql

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 column upcount.

like image 555
BigDataLearner Avatar asked Apr 18 '14 00:04

BigDataLearner


People also ask

How do I update my field in Cassandra?

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.

How do I change the datatype of a column in Cassandra?

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.]

How do you update multiple columns in Cassandra?

Specify other column values using SET. To update multiple columns, separate the name-value pairs using commas.

How does update work in Cassandra?

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.


1 Answers

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

like image 109
cevaris Avatar answered Sep 17 '22 15:09

cevaris