Database Reference
In-Depth Information
Automatically generating UUIDs
In the status updates we've created so far, we've used predetermined UUIDs that were gen-
erated on May 29, 2014. For this reason, the timestamp encoded in the UUIDs doesn't
really tell us anything useful about when the rows were created. However, in the general
case, we would like to encode useful data in the UUID: in particular, the timestamp at
which the row itself was created.
Libraries that generate Version 1 UUIDs are available for just about any programming lan-
guage, but Cassandra also gives us a built-in CQL function to generate a UUID from the
current time, the NOW function. Let's use that function to insert a few new status updates:
INSERT INTO "user_status_updates" ("username", "id", "body")
VALUES ('alice', NOW(), 'Alice Update 1');
INSERT INTO "user_status_updates" ("username", "id", "body")
VALUES ('bob', NOW(), 'Bob Update 1');
INSERT INTO "user_status_updates" ("username", "id", "body")
VALUES ('alice', NOW(), 'Alice Update 2');
INSERT INTO "user_status_updates" ("username", "id", "body")
VALUES ('bob', NOW(), 'Bob Update 2');
INSERT INTO "user_status_updates" ("username", "id", "body")
VALUES ('alice', NOW(), 'Alice Update 3');
INSERT INTO "user_status_updates" ("username", "id", "body")
VALUES ('bob', NOW(), 'Bob Update 3');
Instead of explicitly specifying a UUID constant for the id field, we used the NOW function
to generate a new and unique UUID for each row we inserted.
Note
While the NOW function is quite convenient, particularly in the CQL shell, it comes with
one major downside. Since a CQL INSERT does not give any feedback on the results of
the operation, you won't actually know what UUID the NOW function generates. Sometimes
this is fine, but in many cases your application would want to perform further business lo-
gic that requires knowing the primary key of the record that was just created. In these
cases, it's better to use a library to generate UUIDs at the application level and provide
them explicitly as literals in the INSERT statement.
Search WWH ::




Custom Search