如何以编程方式知道 Cassandra 中 table 的主键

How to programmatically know the primary keys of a table in Cassandra

我正在使用 Datastax driver 访问 cassandra。我的方法需要 cql string paramater。 因为cql是任意的,不知道cql字符串中table的primary keys

在 ResultSet 中,我没有找到与 primary keys 关联的 metadata。 我只能得到 all columnsnamesvalues

我想知道哪些列是主键。 如何programmatically获取cql中table的主键?

public Map<String, Object> search(String cql) {

    SimpleStatement statement = new SimpleStatement(cql);
    ResultSet result = session.execute(statement);
    // ...
}

我不知道任何驱动程序的东西,但如果一切都失败了,你可以执行以下操作:

cqlsh> select column_name, kind from system_schema.columns where keyspace_name ='test' and table_name = 'authorization';

 column_name             | kind
-------------------------+---------------
 authorization_reference |       regular
            order_number | partition_key
              partner_id |    clustering
        sales_channel_id |    clustering

可以使用TableMetadata.getPrimaryKey()方法

这里是获取键空间'test'和table主键的示例演示ashraful_test

try (Cluster cluster = Cluster.builder().addContactPoints("127.0.0.1").withCredentials("cassandra", "cassandra").build(); Session session = cluster.connect("test")) {
    System.out.println(cluster.getMetadata().getKeyspace(session.getLoggedKeyspace()).getTable("ashraful_test").getPrimaryKey());
}