Apache Cassandra

Cassandra Fetch Write Timestamp

“When working with databases, you will often see a lot of sequential or near sequential operations which can quickly transform your database within a short timeframe. However, it can be necessary to traceback when a given operation occurs in your database.

In Cassandra, every table has a timestamp value that contains the Epoch timestamp that a given write operation was executed on a column.

In this tutorial, we will show you how to use the writeTime() function to fetch the timestamp that a specific column was inserted into a table.”

Sample Table and Records

Let us take the statements below that creates a table and insert sample records into a given table.

create table products(
id int,
product_name text,
price int,
qty int,
primary key(id)
);
begin batch
insert into products(id, product_name, price, qty)
values (1, 'product_1', 100, 5640);

insert into products(id, product_name, price, qty)
values (2, 'product_2', 800, 550);

insert into products(id, product_name, price, qty)
values (3, 'product_3', 500, 5550);

insert into products(id, product_name, price, qty)
values (4, 'product_3', 150, 540);

insert into products(id, product_name, price, qty)
values (5, 'product_4', 160, 260);

insert into products(id, product_name, price, qty)
values (6, 'product_5', 130, 5640);
apply batch;

in the example above, we use batch processing to insert multiple records into the table. Although you can specify which statement the server should allocate a timestamp, we simply left it out.

You can learn more about Cassandra batch processing in our tutorial on the topic.

Cassandra Fetch Write Timestamp

To fetch the timestamp that the value “product_4” was added into the product_name column, we can run the query as shown:

select writetime(product_name) from products where id = 4;

This should return the timestamp for the specified write as shown:

writetime(product_name)
-------------------------
1664055523819399
(1 rows)

The above resolves to the human time as:

Saturday, September 24, 2022 9:38:43.819 PM

Conclusion

In this post, we discussed using the writeTime() function to fetch the timestamp at which a specific write occurred in a table.

Thanks for reading & catch you in the next one.

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