Skip to content Skip to sidebar Skip to footer

How To Add Cassandra Table Column Dynamically?

I'm trying to add a new columns to cassandra table dynamically. I'm using below version - cqlsh 5.0.1 I'm using python to interact with Cassandra. I have one python list which I w

Solution 1:

Cassandra internally stores data as rows, each row has a key (Partition key) and dynamic number of columns (clustering key). So, you can use Clustering Key value for your column names, e.g

CREATETABLE my_data (
     pk text,
     column text,
     value text,
     PRIMARY KEY (pk, column)
); 

Insert new columns and values by a regular INSERT query:

INSERTINTO my_data (pk, column, value) VALUES ('pk1', 'A', 'value A'); 
INSERTINTO my_data (pk, column, value) VALUES ('pk1', 'B', 'value B');
INSERTINTO my_data (pk, column, value) VALUES ('pk1', 'C', 'value C');
...  

Get all columns for pk1:

SELECT*FROM my_data WHERE pk='pk1';

Updated

Assume, you have table my_data as described above and you want to add some columns and data for a specific pk value. In python code perform insert query:

pk = 'pk'
columns_data = {'A':'valueforA','B':'value  forB','C': 'valueforC'} #dynamic column data
forcol_name, col_value in columns_data.iteritems():
   try:
      session.execute("INSERT INTO my_data (pk, column, value) VALUES (%s, %s, %s)", (pk, col_name, col_value))
   except:
      pass

Moreover, you can use asynchronous driver's methods, to achieve more performance of inserting.

Post a Comment for "How To Add Cassandra Table Column Dynamically?"