Create KeySpace and Table
To create a keyspace and table in Apache Cassandra, you can use the Cassandra Query Language (CQL). Below are the steps to create a keyspace and table:
1. Start cqlsh:
Open a command prompt or terminal window and start the cqlsh command-line tool. This tool allows you to interact with the Cassandra cluster using CQL.
cqlsh
2. Create a Keyspace:
Use the CREATE KEYSPACE statement to create a keyspace. Keyspaces are the top-level containers for tables in Cassandra.
CREATE KEYSPACE IF NOT EXISTS my_keyspace
WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1};
This statement creates a keyspace named my_keyspace with a replication strategy of SimpleStrategy and a replication factor of 1. Adjust the replication strategy and replication factor based on your requirements.
3. Use the Keyspace:
After creating the keyspace, use the USE statement to switch to the newly created keyspace.
USE my_keyspace;
4. Create a Table:
Now, you can create a table within the keyspace using the CREATE TABLE statement.
CREATE TABLE IF NOT EXISTS users (
user_id UUID PRIMARY KEY,
name TEXT,
email TEXT
);
This statement creates a table named users with columns user_id, name, and email. The user_id column is designated as the primary key.
5. Verify:
You can verify that the keyspace and table are created successfully by describing them using the DESCRIBE command:
DESCRIBE KEYSPACES;
DESCRIBE TABLES;
These commands will display the list of keyspaces and tables in the Cassandra cluster.
6. Insert Data (Optional):
If desired, you can insert data into the newly created table using the INSERT statement:
INSERT INTO users (user_id, name, email) VALUES (uuid(), 'John Doe', 'john@example.com');
Replace the values with your own data.
7. Query Data (Optional):
You can query the data from the table using the SELECT statement:
SELECT * FROM users;
This will retrieve all rows from the users table.
8. Exit cqlsh:
To exit the cqlsh shell, simply type exit or press Ctrl + D.
exit
That's it! You have successfully created a keyspace and table in Apache Cassandra and performed basic operations. Adjust the keyspace, table schema, and data as needed for your application requirements.
Leave a Comment