How can I create a keyspace if not exists using cassandra nodejs-driver.

521 views
Skip to first unread message

Soumya Dash

unread,
Apr 21, 2017, 5:58:48 AM4/21/17
to DataStax Node.js Driver for Apache Cassandra Mailing List

If I use the client.execute with query as "CREATE KEYSPACE samplekeyspace WITH REPLICATION = {  ‘class’  :  ‘SimpleStrategy’, ‘replication_factor’ : 1 } , it throws error as Keyspace 'samplekeyspace' does not exist. 

In my application I need the keyspace to be created on the fly if not exists.

Can someone please help me with this scenario ?

Jorge Bay Gondra

unread,
Apr 21, 2017, 6:23:59 AM4/21/17
to nodejs-dr...@lists.datastax.com
Hi,
If I understood the question correctly and you are providing a keyspace that does not yet exists on the client options, something like this:

const createKsQuery = "CREATE KEYSPACE samplekeyspace WITH REPLICATION = {  'class'  : 'SimpleStrategy', 'replication_factor' : 1 }";

const client = new Client({ 
  contactPoints: contactPoints,
  keyspace: 'samplekeyspace'
});

client
  .connect()
  .then(() => client.execute(createKsQuery));

Then, it will fail because you are trying to connect initially to a keyspace that does not yet exists...

You should not provide a keyspace and issue a USE statement after the keyspace has been created, something like this:

// Do not provide the keyspace here
const client = new Client({ contactPoints: contactPoints });

client
  .connect()
  .then(() => client.execute(createKsQuery))
  .then(() => client.execute("USE samplekeyspace"));

This way, all the connections in the pool will switch to samplekeyspace as the active keyspace.

Does it answer your question?

Jorge


--
You received this message because you are subscribed to the Google Groups "DataStax Node.js Driver for Apache Cassandra Mailing List" group.
To unsubscribe from this group and stop receiving emails from it, send an email to nodejs-driver-user+unsub...@lists.datastax.com.

Reply all
Reply to author
Forward
0 new messages