How to create, alter and drop Keyspaces in Cassandra

Last updated on May 30 2022
Lalit Kolgaonkar

Table of Contents

How to create, alter and drop Keyspaces in Cassandra

Cassandra – Create Keyspace

Creating a Keyspace using Cqlsh

A keyspace in Cassandra is a namespace that defines data replication on nodes. A cluster contains one keyspace per node. Given below is the syntax for creating a keyspace using the statement CREATE KEYSPACE.

Syntax

CREATE KEYSPACE <identifier> WITH <properties>

i.e.

CREATE KEYSPACE “KeySpace Name”

WITH replication = {‘class’: ‘Strategy name’, ‘replication_factor’ : ‘No.Of   replicas’};

 

CREATE KEYSPACE “KeySpace Name”

WITH replication = {‘class’: ‘Strategy name’, ‘replication_factor’ : ‘No.Of  replicas’}

 

AND durable_writes = ‘Boolean value’;

The CREATE KEYSPACE statement has two properties: replication and durable_writes.

Replication

The replication option is to specify the Replica Placement strategy and the number of replicas wanted. The following table lists all the replica placement strategies.

Strategy name Description
Simple Strategy’ Specifies a simple replication factor for the cluster.
Network Topology Strategy Using this option, you can set the replication factor for each data-center independently.
Old Network Topology Strategy This is a legacy replication strategy.

Using this option, you can instruct Cassandra whether to use commitlog for updates on the current KeySpace. This option is not mandatory and by default, it is set to true.

Example

Given below is an example of creating a KeySpace.

  • Here we are creating a KeySpace named Tecklearn.
  • We are using the first replica placement strategy, i.e.., Simple Strategy.
  • And we are choosing the replication factor to 1 replica.

cqlsh.> CREATE KEYSPACE tecklearn

WITH replication = {‘class’:’SimpleStrategy’, ‘replication_factor’ : 3};

Verification

You can verify whether the table is created or not using the command Describe. If you use this command over keyspaces, it will display all the keyspaces created as shown below.

cqlsh> DESCRIBE keyspaces;

 

tecklearn system system_traces

Here you can observe the newly created KeySpace tecklearn.

Durable_writes

By default, the durable_writes properties of a table is set to true, however it can be set to false. You cannot set this property to simplex strategy.

Example

Given below is the example demonstrating the usage of durable writes property.

cqlsh> CREATE KEYSPACE test

… WITH REPLICATION = { ‘class’ : ‘NetworkTopologyStrategy’, ‘datacenter1’ : 3 }

… AND DURABLE_WRITES = false;

Verification

You can verify whether the durable_writes property of test KeySpace was set to false by querying the System Keyspace. This query gives you all the KeySpaces along with their properties.

cqlsh> SELECT * FROM system_schema.keyspaces;

 

keyspace_name | durable_writes |                                       strategy_class | strategy_options

—————-+—————-+——————————————————+—————————-

 

test |          False | org.apache.cassandra.locator.NetworkTopologyStrategy | {“datacenter1” : “3”}

 

tecklearn |           True |          org.apache.cassandra.locator.SimpleStrategy | {“replication_factor” : “4”}

 

system |           True |           org.apache.cassandra.locator.LocalStrategy | { }

 

system_traces |           True |          org.apache.cassandra.locator.SimpleStrategy | {“replication_factor” : “2”}

 

(4 rows)

Here you can observe the durable_writes property of test KeySpace was set to false.

Using a Keyspace

You can use a created KeySpace using the keyword USE. Its syntax is as follows −

Syntax:USE <identifier>

Example

In the following example, we are using the KeySpace tecklearn.

cqlsh> USE tecklearn;

cqlsh:tecklearn>

Creating a Keyspace using Java API

You can create a Keyspace using the execute() method of Session class. Follow the steps given below to create a keyspace using Java API.

Step1: Create a Cluster Object

First of all, create an instance of Cluster.builder class of com.datastax.driver.core package as shown below.

//Creating Cluster.Builder object

 

Cluster.Builder builder1 = Cluster.builder();

Add a contact point (IP address of the node) using addContactPoint() method of Cluster.Builder object. This method returns Cluster.Builder.

//Adding contact point to the Cluster.Builder object

 

Cluster.Builder builder2 = build.addContactPoint( “127.0.0.1” );

Using the new builder object, create a cluster object. To do so, you have a method called build() in the Cluster.Builder class. The following code shows how to create a cluster object.

//Building a cluster

Cluster cluster = builder.build();

You can build a cluster object in a single line of code as shown below.

Cluster cluster = Cluster.builder().addContactPoint(“127.0.0.1”).build();

Step 2: Create a Session Object

Create an instance of Session object using the connect() method of Cluster class as shown below.

Session session = cluster.connect( );

This method creates a new session and initializes it. If you already have a keyspace, you can set it to the existing one by passing the keyspace name in string format to this method as shown below.

Session session = cluster.connect(“ Your keyspace name ” );

Step 3: Execute Query

You can execute CQL queries using the execute() method of Session class. Pass the query either in string format or as a Statement class object to the execute() method. Whatever you pass to this method in string format will be executed on the cqlsh.

In this example, we are creating a KeySpace named tp. We are using the first replica placement strategy, i.e., Simple Strategy, and we are choosing the replication factor to 1 replica.

You have to store the query in a string variable and pass it to the execute() method as shown below.

String query = “CREATE KEYSPACE tp WITH replication ”

+ “= {‘class’:’SimpleStrategy’, ‘replication_factor’:1}; “;

session.execute(query);

Step4 : Use the KeySpace

You can use a created KeySpace using the execute() method as shown below.

execute(“ USE tp ” );

Given below is the complete program to create and use a keyspace in Cassandra using Java API.

import com.datastax.driver.core.Cluster;

import com.datastax.driver.core.Session;

 

public class Create_KeySpace {

 

public static void main(String args[]){

 

//Query

String query = “CREATE KEYSPACE tp WITH replication ”

+ “= {‘class’:’SimpleStrategy’, ‘replication_factor’:1};”;

 

//creating Cluster object

Cluster cluster = Cluster.builder().addContactPoint(“127.0.0.1”).build();

 

//Creating Session object

Session session = cluster.connect();

 

//Executing the query

session.execute(query);

 

//using the KeySpace

session.execute(“USE tp”);

System.out.println(“Keyspace created”);

}

}

Save the above program with the class name followed by .java, browse to the location where it is saved. Compile and execute the program as shown below.

$javac Create_KeySpace.java

$java Create_KeySpace

Under normal conditions, it will produce the following output −

Keyspace created

 

 

Cassandra – Alter Keyspace

Altering a KeySpace

ALTER KEYSPACE can be used to alter properties such as the number of replicas and the durable_writes of a KeySpace. Given below is the syntax of this command.

Syntax

ALTER KEYSPACE <identifier> WITH <properties>

i.e.

ALTER KEYSPACE “KeySpace Name”

WITH replication = {‘class’: ‘Strategy name’, ‘replication_factor’ : ‘No.Of  replicas’};

The properties of ALTER KEYSPACE are same as CREATE KEYSPACE. It has two properties: replication and durable_writes.

Replication

The replication option specifies the replica placement strategy and the number of replicas wanted.

Durable_writes

Using this option, you can instruct Cassandra whether to use commitlog for updates on the current KeySpace. This option is not mandatory and by default, it is set to true.

Example

Given below is an example of altering a KeySpace.

  • Here we are altering a KeySpace named Tecklearn.
  • We are changing the replication factor from 1 to 3.

cqlsh.> ALTER KEYSPACE tecklearn

WITH replication = {‘class’:’NetworkTopologyStrategy’, ‘replication_factor’ : 3};

Altering Durable_writes

You can also alter the durable_writes property of a KeySpace. Given below is the durable_writes property of the test KeySpace.

SELECT * FROM system_schema.keyspaces;

 

keyspace_name | durable_writes |                                       strategy_class | strategy_options

—————-+—————-+——————————————————+—————————-

test |          False | org.apache.cassandra.locator.NetworkTopologyStrategy | {“datacenter1″:”3”}

 

tecklearn |           True |          org.apache.cassandra.locator.SimpleStrategy | {“replication_factor”:”4″}

 

system |           True |           org.apache.cassandra.locator.LocalStrategy | { }

 

system_traces |           True |          org.apache.cassandra.locator.SimpleStrategy | {“replication_factor”:”2″}

(4 rows)

ALTER KEYSPACE test

WITH REPLICATION = {‘class’ : ‘NetworkTopologyStrategy’, ‘datacenter1’ : 3}

AND DURABLE_WRITES = true;

Once again, if you verify the properties of KeySpaces, it will produce the following output.

SELECT * FROM system_schema.keyspaces;

keyspace_name | durable_writes |                                       strategy_class | strategy_options

—————-+—————-+——————————————————+—————————-

test |           True | org.apache.cassandra.locator.NetworkTopologyStrategy | {“datacenter1″:”3”}

 

tecklearn |           True |          org.apache.cassandra.locator.SimpleStrategy | {“replication_factor”:”4″}

 

system |           True |           org.apache.cassandra.locator.LocalStrategy | { }

 

system_traces |           True |          org.apache.cassandra.locator.SimpleStrategy | {“replication_factor”:”2″}

 

(4 rows)

Altering a Keyspace using Java API

You can alter a keyspace using the execute() method of Session class. Follow the steps given below to alter a keyspace using Java API

Step1: Create a Cluster Object

First of all, create an instance of Cluster.builder class of com.datastax.driver.core package as shown below.

//Creating Cluster.Builder object

Cluster.Builder builder1 = Cluster.builder();

Add a contact point (IP address of the node) using the addContactPoint() method of Cluster.Builder object. This method returns Cluster.Builder.

//Adding contact point to the Cluster.Builder object

Cluster.Builder builder2 = build.addContactPoint( “127.0.0.1” );

Using the new builder object, create a cluster object. To do so, you have a method called build() in the Cluster.Builder class. The following code shows how to create a cluster object.

//Building a cluster

 

Cluster cluster = builder.build();

You can build the cluster object using a single line of code as shown below.

Cluster cluster = Cluster.builder().addContactPoint(“127.0.0.1”).build();

Step 2: Create a Session Object

Create an instance of Session object using the connect() method of Clusterclass as shown below.

Session session = cluster.connect( );

This method creates a new session and initializes it. If you already have a keyspace, you can set it to the existing one by passing the keyspace name in string format to this method as shown below.

Session session = cluster.connect(“ Your keyspace name ” );

Step 3: Execute Query

You can execute CQL queries using the execute() method of Session class. Pass the query either in string format or as a Statement class object to the execute() method. Whatever you pass to this method in string format will be executed on the cqlsh.

In this example,

  • We are altering a keyspace named tp. We are altering the replication option from Simple Strategy to Network Topology Strategy.
  • We are altering the durable_writes to false

You have to store the query in a string variable and pass it to the execute() method as shown below.

//Query

String query = “ALTER KEYSPACE tp WITH replication ” + “=   {‘class’:’NetworkTopologyStrategy’, ‘datacenter1’:3}” +” AND DURABLE_WRITES = false;”;

session.execute(query);

Given below is the complete program to create and use a keyspace in Cassandra using Java API.

import com.datastax.driver.core.Cluster;

import com.datastax.driver.core.Session;

 

public class Alter_KeySpace {

public static void main(String args[]){

 

//Query

String query = “ALTER KEYSPACE tp WITH replication ” + “= {‘class’:’NetworkTopologyStrategy’, ‘datacenter1’:3}”

+ “AND DURABLE_WRITES = false;”;

 

//Creating Cluster object

Cluster cluster = Cluster.builder().addContactPoint(“127.0.0.1”).build();

 

//Creating Session object

Session session = cluster.connect();

 

//Executing the query

session.execute(query);

 

System.out.println(“Keyspace altered”);

}

}

Save the above program with the class name followed by .java, browse to the location where it is saved. Compile and execute the program as shown below.

$javac Alter_KeySpace.java

$java Alter_KeySpace

Under normal conditions, it produces the following output −

Keyspace Altered

 

 

Cassandra – Drop Keyspace

Dropping a Keyspace

You can drop a KeySpace using the command DROP KEYSPACE. Given below is the syntax for dropping a KeySpace.

Syntax

DROP KEYSPACE <identifier>

i.e.

DROP KEYSPACE “KeySpace name”

Example

The following code deletes the keyspace tecklearn.

cqlsh> DROP KEYSPACE tecklearn;

Verification

Verify the keyspaces using the command Describe and check whether the table is dropped as shown below.

cqlsh> DESCRIBE keyspaces;

 

system system_traces

Since we have deleted the keyspace tecklearn, you will not find it in the keyspaces list.

Dropping a Keyspace using Java API

You can create a keyspace using the execute() method of Session class. Follow the steps given below to drop a keyspace using Java API.

Step1: Create a Cluster Object

First of all, create an instance of Cluster.builder class of com.datastax.driver.core package as shown below.

//Creating Cluster.Builder object

Cluster.Builder builder1 = Cluster.builder();

Add a contact point (IP address of the node) using the addContactPoint() method of Cluster.Builder object. This method returns Cluster.Builder.

//Adding contact point to the Cluster.Builder object

Cluster.Builder builder2 = build.addContactPoint( “127.0.0.1” );

Using the new builder object, create a cluster object. To do so, you have a method called build() in the Cluster.Builder class. The following code shows how to create a cluster object.

//Building a cluster

Cluster cluster = builder.build();

You can build a cluster object using a single line of code as shown below.

Cluster cluster = Cluster.builder().addContactPoint(“127.0.0.1”).build();

Step 2: Create a Session Object

Create an instance of Session object using the connect() method of Cluster class as shown below.

Session session = cluster.connect( );

This method creates a new session and initializes it. If you already have a keyspace, you can set it to the existing one by passing the keyspace name in string format to this method as shown below.

Session session = cluster.connect(“ Your keyspace name”);

Step 3: Execute Query

You can execute CQL queries using the execute() method of Session class. Pass the query either in string format or as a Statement class object to the execute() method. Whatever you pass to this method in string format will be executed on the cqlsh.

In the following example, we are deleting a keyspace named tp. You have to store the query in a string variable and pass it to the execute() method as shown below.

String query = “DROP KEYSPACE tp; “;

 

session.execute(query);

Given below is the complete program to create and use a keyspace in Cassandra using Java API.

import com.datastax.driver.core.Cluster;

import com.datastax.driver.core.Session;

 

public class Drop_KeySpace {

 

public static void main(String args[]){

 

//Query

String query = “Drop KEYSPACE tp”;

 

//creating Cluster object

Cluster cluster = Cluster.builder().addContactPoint(“127.0.0.1”).build();

 

//Creating Session object

Session session = cluster.connect();

 

//Executing the query

session.execute(query);

System.out.println(“Keyspace deleted”);

}

}

Save the above program with the class name followed by .java, browse to the location where it is saved. Compile and execute the program as shown below.

$javac Delete_KeySpace.java

$java Delete_KeySpace

Under normal conditions, it should produce the following output −

Keyspace deleted

 

So, this brings us to the end of blog. This Tecklearn ‘How to create, alter and drop Keyspaces in Cassandra’ helps you with commonly asked questions if you are looking out for a job in Cassandra and No-SQL Database Domain.

If you wish to learn HBase and build a career in Cassandra or No-SQL Database domain, then check out our interactive, Apache Cassandra Training, that comes with 24*7 support to guide you throughout your learning period. Please find the link for course details:

https://www.tecklearn.com/course/apache-cassandra-training/

Apache Cassandra Training

About the Course

Take your career to the next level as a certified Apache Cassandra developer by acquiring all the skills through our hands-on training sessions. Tecklearn’s Apache Cassandra Certification Training is designed by professionals as per the industry requirements and demands. This Cassandra Certification Training helps you to master the concepts of Apache Cassandra including Cassandra Architecture, its features, Cassandra Data Model, and its Administration. Our Cassandra certification training course lets you master the high availability NoSQL distributed database.

Why Should you take Apache Cassandra Training?

  • The average salary of a Software Engineer with Apache Cassandra skill is $120,500 per year. – Payscale.com
  • Cassandra is in use at Constant Contact, CERN, Comcast, eBay, GitHub, GoDaddy, Hulu, Instagram, Intuit, Netflix, Reddit, The Weather Channel, and over 1500 more companies that have large, active data sets.
  • Apache Cassandra is one of the most widely used NoSQL database. It offers features such as Fault Tolerance, Scalability, Flexible Data Storage and its efficient writes, which makes it the perfect database for various purposes.

What you will Learn in this Course?

Introduction to Big Data, and Cassandra

  • What is Big Data
  • Limitations of RDBMS
  • NoSQL and it’s Characteristics
  • CAP Theorem
  • Basic concepts of Cassandra
  • Features of Cassandra

Cassandra Data model, Installation and setup

  • Installation of Cassandra
  • Key concepts and deployment of non-relational database, column-oriented database, Data Model – column, column family

Cassandra Architecture

  • Explain the Architecture of Cassandra
  • Different Layers of Cassandra Architecture
  • Partitioning and Snitches
  • Explain Vnodes and How Read and Write Path works
  • Understand Compaction, Anti-Entropy and Tombstone
  • Describe Repairs in Cassandra

Deep Dive into Cassandra Database

  • Describe Different Data Types Used in Cassandra
  • Explain Collection Types
  • Describe What are CRUD Operations
  • Implement Insert, Select, Update and D        elete of various elements
  • Implement Various Functions Used in Cassandra
  • Describe Importance of Roles and Indexing

Backup & Restore and Performance Tuning

  • Learn backup and restore functionality and its importance
  • Create a snapshot using Nodetool utility
  • Restore a snapshot
  • Understand how to choose the right balance of the following resources: memory, CPU, disks, number of nodes, and network.
  • Understand all the logs created by Cassandra
  • Explain the purpose of different log files
  • Configure the log files
  • Learn about Performance Tuning
  • Integration with Spark and Kafka

Advance Modelling

  • Rules of Cassandra data modelling
  • Modelling data around queries
  • Creating table for data queries

Deploying the IDE for Cassandra applications

  • Learning key drivers
  • Deploying the IDE for Cassandra applications and cluster connection
  • Data query implementation

Cassandra Administration

  • Understanding Node Tool Utility
  • Cluster management using Command Line Interface
  • Management and Monitoring using DataStax Ops Center

Cassandra API and Summarization

  • Cassandra client connectivity
  • Connection pool internals
  • Cassandra API
  • Features and concepts of Hector client
  • Thrift, JAVA code and Summarization

Got a question for us? Please mention it in the comments section and we will get back to you.

0 responses on "How to create, alter and drop Keyspaces in Cassandra"

Leave a Message

Your email address will not be published. Required fields are marked *