Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cassandra UPDATE primary key value

I understand that this is not possible using an UPDATE.

What I would like to do instead, is migrate all rows with say PK=0 to new rows where PK=1. Are there any simple ways of achieving this?

like image 446
greenimpala Avatar asked Nov 19 '14 16:11

greenimpala


People also ask

Is it possible to update primary key in Cassandra?

You cannot update any column in the primary key because that would change the primary key for the record.

Can we update data 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 update my clustering key in Cassandra?

In order to point non-primary columns for updating/deleting, it needs to parse through styleid -> sequence partition to hit the columns. Primary key once created can't be changed as it represents how data is stored in Cassandra. Hence updating 'sequence' here is not possible. Save this answer.

Is insert and update same in Cassandra?

Is insert and update same in Cassandra? Insert, Update, and Upsert Because Cassandra uses an append model, there is no fundamental difference between the insert and update operations. If you insert a row that has the same primary key as an existing row, the row is replaced.


1 Answers

For a relatively simple way, you could always do a quick COPY TO/FROM in cqlsh.

Let's say that I have a column family (table) called "emp" for employees.

CREATE TABLE stackoverflow.emp (
    id int PRIMARY KEY,
    fname text,
    lname text,
    role text
)

And for the purposes of this example, I have one row in it.

aploetz@cqlsh:stackoverflow> SELECT * FROM emp;

 id | fname | lname | role
----+-------+-------+-------------
  1 | Angel |   Pay | IT Engineer

If I want to re-create Angel with a new id, I can COPY the table's contents TO a .csv file:

aploetz@cqlsh:stackoverflow> COPY stackoverflow.emp TO '/home/aploetz/emp.csv';

1 rows exported in 0.036 seconds.

Now, I'll use my favorite editor to change the id of Angel to 2 in emp.csv. Note, that if you have multiple rows in your file (that don't need to be updated) this is your opportunity to remove them:

2,Angel,Pay,IT Engineer

I'll save the file, and then COPY the updated row back into Cassandra FROM the file:

aploetz@cqlsh:stackoverflow> COPY stackoverflow.emp FROM '/home/aploetz/emp.csv';

1 rows imported in 0.038 seconds.

Now Angel has two rows in the "emp" table.

aploetz@cqlsh:stackoverflow> SELECT * FROM emp;

 id | fname | lname | role
----+-------+-------+-------------
  1 | Angel |   Pay | IT Engineer
  2 | Angel |   Pay | IT Engineer

(2 rows)

For more information, check the DataStax doc on COPY.

like image 86
Aaron Avatar answered Sep 21 '22 15:09

Aaron