How do I retrieve table names in Cassandra using Java?

孤人 提交于 2019-12-10 13:22:19

问题


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.


回答1:


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());



回答2:


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.



来源:https://stackoverflow.com/questions/42469341/how-do-i-retrieve-table-names-in-cassandra-using-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!