How to create Keyspaces in Cassandra by using CQL - Cassandra / CQL Tutorial

How to create Keyspaces in Cassandra by using CQL

Keyspace is like is database schema.It is top level container/namespace in which tables can be created. Keyspace also defines data replication on Nodes.


CREATE keyspace keyspacename WITH options
Replication property is mandatory when we create Keyspace. In syntax we have to use 'class' sub-option which defines replication strategy.  The sub-options depends which replication strategy we choose.


SimpleStrategy defines a replication factor for whole cluster.
CQLSH:techbrotherstutorialsCREATE keyspace techbrotherstutorials 
WITH REPLICATION = {'class': 'SimpleStrategy', 'replication_factor' : 2};

The above script will create Keyspace TechbrothersTutorials with SimpleStrategy with total number of replicas=2 for whole cluster.
NetworkTopologyStrategy is replication strategy that allows to set the replication factor independently for each data-center in cluster.
CQLSH:techbrotherstutorials> CREATE keyspace techbrotherstutorials 
WITH REPLICATION = {'class': 'NetworkTopologyStrategy', 'DC1' : 2, 'DC2' : 1};

The above script will create the keyspace TechBrothersTutorials with 2 replicas in DC1 ( Data Center 1) and 1 replica from DC2 ( Data Center 2).

Durable Writes:
Durable Write is another option that is enabled by default when we create keyspace. Cassandra caches data in memory and flush to persistent storage periodically. In case something goes wrong between two consective flush operations, the cached data can be lost. When we enable Durable Writes for keyspace, Cassanda uses special storage called "Commit Log" which keeps the copy of data in memory which is not flushed to disk.In case of data lost from memory, Data from Commit Log can be used and write to disk. If your data is very important, it make sense to enable this property even there will be some extra load on database, if Data is not important you can disable this property.

CQLSH:techbrotherstutorials> CREATE keyspace techbrotherstutorials 
WITH REPLICATION = {'class': 'NetworkTopologyStrategy', 'DC1' : 2, 'DC2' : 1}
AND durable_writes = false;