How to generate TimeUUID in Java/Scala
Asked Answered
D

4

12

Does anyone know how to generate TimeBased UUIDs in Java/Scala?

Here is the column family:

CREATE table col(ts timeuuid)

I'm using Cassandra 1.2.4

Appreciate your help!

Dagmardagna answered 25/7, 2014 at 9:10 Comment(0)
S
9

Cassandra has UUIDGen for generating Timeuuids. The source for this is here:

https://github.com/apache/cassandra/blob/cassandra-2.1/src/java/org/apache/cassandra/utils/UUIDGen.java

Sunlight answered 25/7, 2014 at 9:16 Comment(0)
B
17

If you are using the Datastax drivers you can use the utility class, UUIDs, to generate one

import com.datastax.driver.core.utils.UUIDs;
....
UUID timeBasedUuid = UUIDs.timeBased();
Blois answered 3/4, 2017 at 19:32 Comment(0)
S
9

Cassandra has UUIDGen for generating Timeuuids. The source for this is here:

https://github.com/apache/cassandra/blob/cassandra-2.1/src/java/org/apache/cassandra/utils/UUIDGen.java

Sunlight answered 25/7, 2014 at 9:16 Comment(0)
D
4

i am using the same way for cassandra cli, and for column name i am using

System.currentTimeMillis().toString

scala>     val timestamp = System.currentTimeMillis().toString
timestamp: String = 1406279679674

UPDATE

mainly it depends on your row key if rowKey is your userId or something, then there is no chance of submission of duplicate record in miliseconds but if you think it can be repeat then use

val timestamp = com.eaio.uuid.UUIDGen.newTime().toString
Dispensable answered 25/7, 2014 at 9:13 Comment(0)
S
1

this is work for cassandra 4.x version

first, import libary in build.sbt

libraryDependencies ++= Seq(
  "com.datastax.oss" % "java-driver-core" % "4.15.0"
)

example

import com.datastax.oss.driver.api.core.uuid.Uuids

import java.time.ZonedDateTime

object Test extends App {
  val timeText = "2022-01-01T00:01:01.002345Z"
  val datetime = ZonedDateTime.parse(timeText)
  val uuid = Uuids.endOf(datetime.toInstant.toEpochMilli)
  println(uuid) // e79b51af-6a95-11ec-7f7f-7f7f7f7f7f7f
}

test on cassandra

cqlsh:test> create table aaa (id timeuuid primary key, t text);

cqlsh:test> insert into aaa(id,t) values(e79b51af-6a95-11ec-7f7f-7f7f7f7f7f7f, 't4');

cqlsh:test> select toTimestamp(id), t from aaa;

 system.totimestamp(id)          | t
---------------------------------+----
 2022-01-01 00:01:01.002000+0000 | t4

Saretta answered 23/11, 2022 at 6:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.