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:
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:
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:
For example, to switch to the keyspace “me” that was created earlier, use the following command:
In CQL Shell, Cassandra updates the prompt to reflect the selected keyspace. For example, the following prompt shows the current keyspace as “me”:
You can also enclose the keyspace name with quotation marks. This is useful if the keyspace name contains special characters.
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:
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!