Reputation: 7252
I am working on project that uses cassandra as a NoSql database. I am trying to setup my test framework to be able to work with an arbitrary keyspace to avoid collisions between different tests running at the same time.
I would like to be able to create session against keyspace that might not exists. Essentially what I want is to first check if it exists and if not to create it, and then to connect.
It seems that the Api has catch 22 because in order I to execute command (that could create keyspace) I already have to have connection to an existing keyspace.
What I am missing?
Upvotes: 3
Views: 3182
Reputation: 57788
Have a look through the tutorials in the DataStax documentation, and you should be able to come up with a way to do this. The first part illustrates how to connect to the database cluster. It walks you through coming up with a simple connect
method that is not specific to a keyspace.
private Cluster cluster;
public void connect(String node) {
cluster = Cluster.builder()
.addContactPoint(node)
.build();
}
The next part discusses how to use a session
object to execute CQL statements. You could probably query the schema_keyspaces
table to see if the keyspace in question exists with something like this:
Session session = cluster.connect();
ResultSet results = session.execute("SELECT * FROM system.schema_keyspaces " +
"WHERE keyspace_name = 'myKeyspaceNameGoesHere';");
The tutorial then shows specifically how to create a new keyspace via the Java Driver.
session.execute("CREATE KEYSPACE myKeyspaceNameGoesHere WITH replication " +
"= {'class':'SimpleStrategy', 'replication_factor':3};");
Note that I have pulled the code here from the examples in the docs. You will want to substitute your own keyspace name, replication strategy and factor.
Upvotes: 5