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 Cass
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
CREATE TABLE my_data (
pk text,
column text,
value text,
PRIMARY KEY (pk, column)
);
Insert new columns and values by a regular INSERT query:
INSERT INTO my_data (pk, column, value) VALUES ('pk1', 'A', 'value A');
INSERT INTO my_data (pk, column, value) VALUES ('pk1', 'B', 'value B');
INSERT INTO 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':'value for A','B':'value for B','C': 'value for C'} #dynamic column data
for col_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.