Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I retrieve table names in Cassandra using Java?

If is use this code in a CQL shell , I get all the names of table(s) in that keyspace.

DESCRIBE TABLES;

I want to retrieve the same data using ResulSet . Below is my code in Java.

String query = "DESCRIBE TABLES;";

ResultSet rs = session.execute(query);
for(Row row  : rs) {
    System.out.println(row);
}   

While session and cluster has been initialized earlier as:

Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build();
Session session = cluster.connect("keyspace_name");

Or I like to know Java code to retrieve table names in a keyspace.

like image 592
Kangkan Lahkar Avatar asked Feb 26 '17 13:02

Kangkan Lahkar


1 Answers

The schema for the system tables change between versions quite a bit. It is best to rely on drivers Metadata that will have version specific parsing built in. From the Java Driver use

Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build();
Collection<TableMetadata> tables = cluster.getMetadata()
    .getKeyspace("keyspace_name")
    .getTables(); // TableMetadata has name in getName(), along with lots of other info

// to convert to list of the names
List<String> tableNames = tables.stream()
        .map(tm -> tm.getName())
        .collect(Collectors.toList());
like image 113
Chris Lohfink Avatar answered Sep 30 '22 12:09

Chris Lohfink