How to add cassandra table column dynamically?

后端 未结 1 1770
时光说笑
时光说笑 2021-01-27 19:02

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

相关标签:
1条回答
  • 2021-01-27 19:33

    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.

    0 讨论(0)
提交回复
热议问题