How do I retrieve table names in Cassandra using Java?
Asked Answered
F

2

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.

Footer answered 26/2, 2017 at 13:53 Comment(2)
DESCRIBE only works on the CLI.Outfitter
The how to do in JavaFooter
N
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());
Nomo answered 26/2, 2017 at 20:51 Comment(0)
F
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.

Funds answered 27/2, 2017 at 10:26 Comment(2)
.iterator(); doesnt return a Collection<TableMetadata>, need to change it to IteratorNomo
@ChrisLohfink Thanks for suggesting... I just tried to merge 2 steps into 1 and missed that part.Funds

© 2022 - 2024 — McMap. All rights reserved.