javacassandradatastax-java-driver

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


I'm using Datastax driver to access cassandra. My method takes a cql string paramater. Because the cql is arbitrary, I don't know the primary keys of the table in the cql string.

In ResultSet, I didn't find the metadata associated with the primary keys. I can only get the names and values of all columns.

I'd like to know which columns are primary keys. How to programmatically get the primary keys of the table in the cql?

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

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

Solution

  • You can use TableMetadata.getPrimaryKey() method

    Here is a sample demo to get the primary key of keyspace 'test' and 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());
    }