Apache Cassandra

Cassandra Use

In Cassandra, a keyspace refers to the top-level object that acts as a data container. The keyspace manages the replication for each data center in the cluster. In simple terms, think of a keyspace as a database in the context of relational databases.

The keyspace holds the data such as tables, functions, aggregates, materialized views, user-defined types, and more.

Once you create a keyspace in Cassandra, you can set it as the current keyspace within a given session using the USE keyword. Once you switch to a given keyspace, any operations such as create, insert, update, and delete are in the context of the selected keyspace.

This tutorial shows you how to switch to a specific keyspace using the USE keyword in CQL Shell.

Let’s dive in.

Creating an Example Keyspace to Use

Before using a specific keyspace, we must ensure that it exists within the cluster. If you attempt to use a non-existent keyspace, Cassandra returns an error as shown:

cassandra@cqlsh> use me;
InvalidRequest: Error from server: code=2200 [Invalid query] message="Keyspace 'me' does not exist"

We can create a keyspace with the CREATE KEYSPACE keyword. For example:

cassandra@cqlsh> CREATE KEYSPACE me WITH REPLICATION = {'class': 'SimpleStrategy', 'replication_factor': 1};

The previous command creates a keyspace called  “me” using the SimpleStrategy and replication factor of 1.

Cassandra Use Command

Once you create a keyspace, you can switch to it using the USE keyword. The command syntax is as shown:

USE keyspace_name;

For example, to switch to the keyspace “me” that was created earlier, use the following command:

cassandra@cqlsh> USE me;

In CQL Shell, Cassandra updates the prompt to reflect the selected keyspace. For example, the following prompt shows the current keyspace as “me”:

cassandra@cqlsh:me>

You can also enclose the keyspace name with quotation marks. This is useful if the keyspace name contains special characters.

USE "me";

In other cases, you can use a keyspace without switching to it. For example, to select the records from the keyspaces table in the system_schema keyspace, we can run the following command:

cassandra@cqlsh:me> SELECT * FROM system_schema.keyspaces;

In this case, we select the records from the system_schema keyspace using the dot notation.

Conclusion

In this article, you learned how to switch from one keyspace to another in the current Cassandra session using the USE keyword.

Thanks for reading!

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list