Cassandra Create Keyspace

In this article, we will see How to create Cassandra Keyspace with examples.

What is Cassadra keyspace?

CQL stores data in tables, whose schema defines the layout of said data in the table, and those tables are grouped in keyspaces. In RDBMS, we call databases and in Cassandra it is keyspace.

  • keyspace name should be comprised of only alphanumeric characters, cannot be empty and are limited in size to 48 characters.
  • By default, keyspace and table names are case insensitive but case sensitivity can be forced by using double-quotes (“Student” is different from student).

Cassandra Create Keyspace Syntax:

CREATE KEYSPACE [ IF NOT EXISTS ] keyspace_name WITH options

or

CREATE KEYSPACE “KeySpace_Name” WITH replication = {'class': ‘Strategy name’, 'replication_factor' : ‘No.Of replicas’} AND durable_writes = ‘Boolean value’;

Where options are:

replication: The replication strategy and options to use for the keyspace
durable_writes: Whether to use the commit log for updates on this keyspace

There are two replication strategies:

SimpleStrategy: A simple strategy that defines a replication factor for data to be spread across the entire cluster.
NetworkTopologyStrategy: A production ready replication strategy that allows to set the replication factor independently for each data-center.

  • The replication property is mandatory
  • Replication Factor: Replication factor is the number of replicas of data placed on different nodes.

Cassandra Create Keyspace Examples:

1. Lets create a keyspace named ‘r2schools’.

CREATE KEYSPACE r2schools WITH replication = {'class':'SimpleStrategy', 'replication_factor' : 1};

Cassandra Create Keyspace

2. Verify the keyspace created or not by running any of three commands:

describe KEYSPACE r2schools; describe KEYSPACES; SELECT * FROM system_schema.keyspaces;

Output of above queries:

3, Create a keyspace with replication class as NetworkTopologyStatgey:

CREATE KEYSPACE test1 with replication={'class':'NetworkTopologyStrategy', 'datacenter1': 1} AND durable_writes = true;

4. If we want to alter the keyspace options, for example changing the replication_factor from 1 to 2. Then, run the below command.

alter keyspace r2schools with replication={'class':'SimpleStrategy','replication_factor':2};

5. Now if we want to drop a Cassandra keyspace, use the drop statement like below:

drop keyspace test1;

We can verify whether keyspace is dropped from Cassandra or not by running the below command:

select * from system_schema.keyspaces;

So in this article, we have seen Cassandra CREATE Keyspace syntax, rules, strategies and examples.