How to get current timestamp with CQL while using Command Line?

user2467545 picture user2467545 · Oct 27, 2013 · Viewed 85.4k times · Source

I am trying to insert into my CQL table from the command line. I am able to insert everything. But I am wondering if I have a timestamp column, then how can I insert into timestamp column from the command line? Basically, I want to insert current timestamp whenever I am inserting into my CQL table -

Currently, I am hardcoding the timestamp whenever I am inserting into my below CQL table -

CREATE TABLE TEST (ID TEXT, NAME TEXT, VALUE TEXT, LAST_MODIFIED_DATE TIMESTAMP, PRIMARY KEY (ID));

INSERT INTO TEST (ID, NAME, VALUE, LAST_MODIFIED_DATE) VALUES ('1', 'elephant',  'SOME_VALUE', 1382655211694);

Is there any way to get the current timestamp using some predefined functions in CQL so that while inserting into above table, I can use that method to get the current timestamp and then insert into above table?

Answer

lorcan picture lorcan · Oct 28, 2013

You can use the timeuuid functions now() and dateof() (or in later versions of Cassandra, toTimestamp()), e.g.,

INSERT INTO TEST (ID, NAME, VALUE, LAST_MODIFIED_DATE)
                  VALUES ('2', 'elephant',  'SOME_VALUE', dateof(now()));

The now function takes no arguments and generates a new unique timeuuid (at the time where the statement using it is executed). The dateOf function takes a timeuuid argument and extracts the embedded timestamp. (Taken from the CQL documentation on timeuuid functions).

Cassandra >= 2.2.0-rc2

dateof() was deprecated in Cassandra 2.2.0-rc2. For later versions you should replace its use with toTimestamp(), as follows:

INSERT INTO TEST (ID, NAME, VALUE, LAST_MODIFIED_DATE)
                  VALUES ('2', 'elephant',  'SOME_VALUE', toTimestamp(now()));