how to get the list of all table of a key space in cassandra
Question
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.
OTHER TIPS
You can run:
select * from system.schema_columnfamilies where keyspace_name='MyKeySpace';
It runs against the "system" keyspace.
Get column names:
SELECT column_name FROM system.schema_columns WHERE keyspace_name = 'KeySpaceName' AND columnfamily_name = 'TableName';
Get column family names, i.e., table names:
select columnfamily_name from system.schema_columnfamilies where keyspace_name='KeySpaceName';
There is the option to use cluster metadata as well to get a string listing of keyspaces like so
var cluster = Cluster.Builder().AddContactPoints("IPAddress").Build();
var keyspaces = cluster.Metadata.GetKeyspaces();
foreach (var keyspaceName in keyspaces)
{
Console.WriteLine(keyspaceName);
}