Search code examples
c#databasecassandradatastaxcqlsh

how to get the list of all table of a key space in cassandra


I am new to cassandra, I am currently using CassandraCSharpDriver in a dummy application. I want to get the list of all the tables a user has described in a given key space.

        Cluster cluster = Cluster.Builder().AddContactPoints("IPAddress").Build();
        Session session = cluster.Connect("MyKeySpace");

In this code I want to get the list of all the tables of MyKeySpace


Solution

  • I'll run through how I would prepare that list of tables with the DataStax Cassandra C# driver:

    Connect to your cluster:

    Cluster cluster = Cluster.Builder().AddContactPoints("IPAddress").Build();
    Session session = cluster.Connect();
    

    I'll create a List<String> and use a prepared statement (because that's just a good idea) to bind the name of your keyspace. My CQL statement is only selecting columnfamily_name, which should be what you need.

    List<String> tableList = new List<String>();
    
    String strCQL = "SELECT columnfamily_name "
        + "FROM system.schema_columnfamilies WHERE keyspace_name=? ";
    PreparedStatement pStatement = _session.Prepare(strCQL);
    BoundStatement boundStatement = new BoundStatement(pStatement);
    boundStatement.Bind("MyKeySpace");
    

    Now I'll execute the statement, iterate through the results, and add each table name to the List I created above.

    RowSet results = session.Execute(boundStatement);
    
    foreach (Row result in results.GetRows())
    {
        tableName = result.GetValue<String>("columnfamily_name");
        tableList.Add(tableName);
    }
    

    Now you should have a list of tables that you can add to your UI.