Apache Cassandra

Cassandra Show Column TTL

“Apache Cassandra a Time to Live or TTL value for the data in a given column. You can use the TTL value in an INSERT or UPDATE statement allowing the data in that column to expire after the duration is elapsed.”

In this post, we will discuss how you can set and get the TTL value of a given column using the INSERT statement and TTL function, respectively.

Cassandra Create Column With TTL Value

The following queries create a keyspace and a new table to hold the target data.

drop keyspace if exists zero_day;

create keyspace zero_day
with replication = {
'class': 'SimpleStrategy',
'replication_factor': 1
};
use zero_day;

create table records(
id int,
cve_number text,
report_date date,
affected_vendor text,
severity float,
primary key(id)
);

We can then insert data with TTL values as shown in the queries below:

begin batch
insert into records(id, cve_number, report_date, affected_vendor, severity)
values (1, 'CVE-2021-33852', '2022-12-02', 'WordPress', 6.0) using ttl 120;

insert into records(id, cve_number, report_date, affected_vendor, severity)
values (2, 'CVE-2020-14723', '2020-01-11', 'Oracle', 8.2) using ttl 180;

insert into records(id, cve_number, report_date, affected_vendor, severity)
values (3, 'CVE-2019-19306', '2019-10-14', 'Zoho', 5.4) using ttl 240;

insert into records(id, cve_number, report_date, affected_vendor, severity)
values (4, 'CVE-2021-33850', '2021-10-18', 'Microsoft', 5.0) using ttl 300;

insert into records(id, cve_number, report_date, affected_vendor, severity)
values (5, 'CVE-2020-24600', '2020-07-01', 'Shilpi', 8.6) using ttl 360;
apply batch;

The insert statements add data with TTL values to the specified table. Keep in mind that the TTL value is defined in seconds.

Cassandra Show TTL Values

To show the TTL value of a given column, use the TTL function as shown in the example below:

cassandra@cqlsh:zero_day> select ttl(cve_number) from records where id=5;

The query above should display the remaining TTL value for the row with id of 5.

An example output is as shown:

@ Row 1
-----------------+-----
ttl(cve_number) | 169
(1 rows)

Once the TTL value is elapsed, the data is removed from the table as shown:

cassandra@cqlsh:zero_day> select ttl(cve_number) from records where id=3;

The row does not exist in this case as the data has been removed.

ttl(cve_number)
-----------------
(0 rows)

Conclusion

In this tutorial, we discussed how to set and get the TTL value of a given row in Cassandra.

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