Apache Cassandra

Cassandra Truncate

In this article, you will learn how to use the Apache Cassandra TRUNCATE command. This command allows you to remove all the data from a table without deleting the table or its schema.

In simple terms, the TRUNCATE command allows you to reset the data stored in a table allowing you to restore or insert new data.

Cassandra Truncate Command Syntax

The TRUNCATE command syntax is as shown:

TRUNCATE [TABLE] [keyspace.table_name]

You can omit the TABLE keyword in the syntax above. The command will perform a similar action.

Keep in mind that the TRUNCATE command sends the JMX command to all the nodes in the cluster that contains the data of the target. This allows the nodes to synchronize and stay up to date with the recent data changes. If either of the nodes in the cluster is down, the command will fail and return an error.

Creating Sample Table and Data

For illustration purposes, we will create a sample keyspace and table. The commands are as shown in the snippets below:

cqlsh> create keyspace height_info
   ... with replication = {
   ... 'class': 'SimpleStrategy',
   ... 'replication_factor': 1};
cqlsh> USE height_info;
cqlsh:height_info> CREATE TABLE recipients(
               ... id int,
               ... username text,
               ... height int,
               ... PRIMARY KEY(id, height));

We can then insert sample data as shown in the commands below:

cqlsh:height_info> INSERT INTO recipients(id, username, height) values (0, 'user1', 210);
cqlsh:height_info> INSERT INTO recipients(id, username, height) values (1, 'user2', 115);
cqlsh:height_info> INSERT INTO recipients(id, username, height) values (2, 'user3', 202);
cqlsh:height_info> INSERT INTO recipients(id, username, height) values (3, 'user4', 212);
cqlsh:height_info> INSERT INTO recipients(id, username, height) values (4, 'user5', 216);

Example Truncation Operation

The data stored in the table before truncation is as shown:

SELECT * FROM recipients;

We can truncate the table as shown:

cqlsh:height_info> TRUNCATE TABLE height_info.recipients;

Finally, we can confirm the data is removed from the table as:

cqlsh:height_info> SELECT * FROM recipients;

You will notice that the table still exists including all the schema definitions. However, the data from the table has been removed leaving an empty table.

Keep in mind that the TRUNCATE operation is irreversible. Be cautious in its usage and potential data loss.

Conclusion

In this post, you learned how to remove all the data from a table while preserving the table schema using the CQL TRUNCATE command.

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