Question

I need to check if certain keyspace exists in Cassandra database. I need to write smth like this:

if (keyspace KEYSPACE_NAME not exists) create keyspace KEYSPACE_NAME;

There's a command describe keyspace, but can I somehow retrieve information from it in cql script?

Was it helpful?

Solution

As of this moment, cql grammar does not provide create keyspace if not exists. Probably in the future, they will add this feature. The one come close to this, would be this improvement, maybe they will add in for create keyspace too. shrugs

You can probably do something similar using CQL in python or in any Cassandra clients. I have a simple create keyspace if not exists written in java.

try
{
    if (cluster.describeKeyspace("new_keyspace") == null)
    {
        System.out.println("create new keyspace");
        KeyspaceDefinition ksdef = HFactory.createKeyspaceDefinition("new_keyspace");
        cluster.addKeyspace(ksdef);
    }
    else
    {
        System.out.println("keyspace exists");
    }
}
catch (HectorException e)
{   
}

OTHER TIPS

Just providing fresh information. As of CQL3 while creating a keyspace you can add if statement like this

CREATE KEYSPACE IF NOT EXISTS Test
    WITH replication = {'class': 'SimpleStrategy',
                        'replication_factor' : 3}

According to: https://issues.apache.org/jira/browse/CASSANDRA-2477, as of Cassandra 1.1, you can now do:

USE system;
SELECT * FROM schema_keyspaces;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top