How to check if a Cassandra table exists

后端 未结 3 1427
南旧
南旧 2021-02-07 01:35

Is there an easy way to check if table (column family) is defined in Cassandra using CQL (or API perhaps, using com.datastax.driver)?

Right now I am leaning towards exec

相关标签:
3条回答
  • 2021-02-07 01:59

    As of 1.1 you should be able to query the system keyspace, schema_columnfamilies column family. If you know which keyspace you want to check, this CQL should list all column families in a keyspace:

    SELECT columnfamily_name
    FROM schema_columnfamilies WHERE keyspace_name='myKeyspaceName';
    

    The report describing this functionality is here: https://issues.apache.org/jira/browse/CASSANDRA-2477

    Although, they do note that some of the system column names have changed between 1.1 and 1.2. So you might have to mess around with it a little to get your desired results.

    Edit 20160523 - Cassandra 3.x Update:

    Note that for Cassandra 3.0 and up, you'll need to make a few adjustments to the above query:

    SELECT table_name 
    FROM system_schema.tables WHERE keyspace_name='myKeyspaceName';
    
    0 讨论(0)
  • 2021-02-07 01:59

    I just needed to manually check for the existence of a table using cqlsh. Possibly useful general info.

    describe keyspace_name.table_name
    

    If it doesn't exist you'll get 'table_name' not found in keyspace 'keyspace' If it does exist you'll get a description of the table.

    0 讨论(0)
  • 2021-02-07 02:16

    The Java driver (since you mentioned it in your question) also maintains a local representation of the schema.

    Driver 3.x and below:

    KeyspaceMetadata ks = cluster.getMetadata().getKeyspace("myKeyspace");
    TableMetadata table = ks.getTable("myTable");
    boolean tableExists = (table != null);
    

    Driver 4.x and above:

    Metadata metadata = session.getMetadata();
    boolean tableExists =
      metadata.getKeyspace("myKeyspace")
        .flatMap(ks -> ks.getTable("myTable"))
        .isPresent();
    
    0 讨论(0)
提交回复
热议问题