Bringing together the Apache Cassandra experts from the community and DataStax.

Want to learn? Have a question? Want to share your expertise? You are in the right place!

Not sure where to begin? Getting Started

 

question

Erick Ramirez avatar image
Erick Ramirez asked ·

What is the Java Driver syntax for inserting a timestamp with QueryBuilder?

A user had a table with a timestamp column like this:

CREATE TABLE comments (
    comment_id text,
    username text,
    comment_time timestamp,
    PRIMARY KEY (comment_id)
)

Attempts to insert a value using QueryBuilder.now() :

preparedInsert = session.prepare(QueryBuilder
    .insertInto(ks_name, table_name)
    .value("comment_id", QueryBuilder.bindMarker())
    .value("username", QueryBuilder.bindMarker())
    .value("comment_time", QueryBuilder.now())
);

results in the following exception:

com.datastax.driver.core.exceptions.InvalidQueryException: Type error: cannot assign result of function system.now (type timeuuid) to update_time (type timestamp)

What is the syntax for inserting a timestamp?

java driver
10 |1000 characters needed characters left characters exceeded

Up to 8 attachments (including images) can be used with a maximum of 1.0 MiB each and 10.0 MiB total.

1 Answer

Erick Ramirez avatar image
Erick Ramirez answered ·

Cause

As the exception message states, the call to now() returns a timeuuid data type instead of timestamp.

Solution

In Java driver 4, convert the return value to a timestamp with the method toTimestamp():

QueryBuilder.toTimestamp(QueryBuilder.now());

In earlier versions of the Java driver, you will need to create a function call toTimestamp with fcall():

QueryBuilder.fcall("toTimestamp",QueryBuilder.now());

Credit

Thanks to Alex Ott (@alexott_en) for the solution.

Share
10 |1000 characters needed characters left characters exceeded

Up to 8 attachments (including images) can be used with a maximum of 1.0 MiB each and 10.0 MiB total.