【问题标题】:How do I retrieve table names in Cassandra using Java?如何使用 Java 在 Cassandra 中检索表名?
【发布时间】:2017-07-17 02:20:47
【问题描述】:

如果在 CQL shell 中使用此代码,我将获得该键空间中所有表的名称。

DESCRIBE TABLES;

我想使用 ResulSet 检索相同的数据。以下是我的 Java 代码。

String query = "DESCRIBE TABLES;";

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

虽然会话和集群之前已初始化为:

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

或者我想知道在键空间中检索表名的 Java 代码。

【问题讨论】:

  • DESCRIBE 仅适用于 CLI。
  • Java 中的操作方法

标签: cassandra cql cql3 nosql


【解决方案1】:

系统表的架构在版本之间会有很大的变化。最好依赖将具有内置版本特定解析的驱动程序元数据。从 Java 驱动程序使用

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

    上面的代码将在传递的键空间中为您提供表名,而与使用的 cassandra 版本无关。

    【讨论】:

    • .iterator(); 不返回 Collection&lt;TableMetadata&gt;,需要将其更改为 Iterator
    • @ChrisLohfink 感谢您的建议...我只是尝试将 2 个步骤合并为 1 个步骤并错过了那部分。
    猜你喜欢
    • 2018-08-10
    • 2017-09-23
    • 2015-03-15
    • 1970-01-01
    • 2012-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-01
    相关资源
    最近更新 更多