13

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?

Acelasi Eu
  • 914
  • 2
  • 9
  • 30
Yury Pogrebnyak
  • 4,093
  • 9
  • 45
  • 78

3 Answers3

37

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}
Alexis Wilke
  • 19,179
  • 10
  • 84
  • 156
fgakk
  • 1,289
  • 1
  • 15
  • 26
10

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;
Philipp Claßen
  • 41,306
  • 31
  • 146
  • 239
Tao Starbow
  • 361
  • 3
  • 10
  • I'm sorry, I just clicked `accept edit` by mistake. Please don't add stuff that changes the context of questions to edits. The `USE system;` in the suggested edit is one such example. – Benjamin Gruenbaum Jun 12 '13 at 23:36
  • The problem is that system tables tend to change (quickly) over time. It can be a nightmare to support such code, especially if you have to have legacy support for various users. In CQL 3.x, the info is now in a keyspace named `system_schema`... – Alexis Wilke Jul 08 '16 at 16:51
10

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)
{   
}
Alexis Wilke
  • 19,179
  • 10
  • 84
  • 156
Jasonw
  • 5,054
  • 7
  • 43
  • 48
  • Note that from what I know, a `describe*` function is rather slow. Hopefully you do not have to use this too often. – Alexis Wilke Jul 08 '16 at 16:44
  • this was answered back in year 2012... unless at this point of time as of this writing, you are still using ancient cassandra, you should really read the current documentation. – Jasonw Jul 09 '16 at 04:50