Cassandra timeuuid column to nanoseconds precision

676 views Asked by At

Cassandra table has timeuuid data type column so how do I see the value of type timeuuid in nanoseconds?

timeuuid:

49cbda60-961b-11e8-9854-134d5b3f9cf8
49cbda60-961b-11e8-9854-134d5b3f9cf9

How to convert this timeuuid to nanoseconds need a select statement like:

select Dateof(timeuuid) from the table a;
1

There are 1 answers

0
Chris Lohfink On

There is a utility method in driver UUIDs.unixTimestamp(UUID id) that returns a normal epoch timestamp that can be converted into a Date object.

Worth noting that ns precision from the time UUID will not necessarily be meaningful. A type 1 uuid includes a timestamp which is the number of 100 nanosecond intervals since the Gregorian calendar was first adopted at midnight, October 15, 1582 UTC. But the driver takes a 1ms timestamp (precision depends on OS really, can be 10 or 40ms precision even) and keeps a monotonic counter to fill the rest of the 10000 unused precision but can end up counting into the future if in a 1ms there are over 10k values (note: performance limitations will ultimately prevent this). This is much more performant and guarantees no duplicates, especially as sub ms time accuracy in computers is pretty meaningless in a distributed system.

So if your looking from a purely CQL perspective theres no way to do it without a UDF, not that there is much value in getting beyond ms value anyway so dateOf should be sufficient. If you REALLY want it though

CREATE OR REPLACE FUNCTION uuidToNS (id timeuuid)
  CALLED ON NULL INPUT RETURNS bigint
  LANGUAGE java AS '
    return id.timestamp();
  ';

Will give you the 100ns's from October 15, 1582. To translate that to nanoseconds from epoc, mulitply it by 100 to convert to nanos and add the difference from epoch time (-12219292800L * 1_000_000_000 in nanos). This might overflow longs so might need to use something different.