8

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.

mkobit
  • 43,979
  • 12
  • 156
  • 150
Kangkan Lahkar
  • 267
  • 5
  • 16

2 Answers2

7

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());
mkobit
  • 43,979
  • 12
  • 156
  • 150
Chris Lohfink
  • 16,150
  • 1
  • 29
  • 38
4
Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build();
Metadata metadata = cluster.getMetadata();
Iterator<TableMetadata> tm = metadata.getKeyspace("Your Keyspace").getTables().iterator();

while(tm.hasNext()){
    TableMetadata t = tm.next();
    System.out.println(t.getName());
}

The above code will give you table names in the passed keyspace irrespective of the cassandra version used.

mkobit
  • 43,979
  • 12
  • 156
  • 150
undefined_variable
  • 6,180
  • 2
  • 22
  • 37