cassandradatastaxcqlcassandra-python-driver

DS201: How to get value of "type timeuuid" while inserting into cassandra using Python Driver?


This is my first query on the forum so please correct if my understanding are wrong.

I am executing exercise Application Driver Connection from DS201.

Table is as follows:

cqlsh:killrvideo> SELECT * FROM videos_by_tag ;

       tag | added_date                      | video_id                             | title
-----------+---------------------------------+--------------------------------------+------------------------------  
  datastax | 2013-10-16 00:00:00.000000+0000 | 4845ed97-14bd-11e5-8a40-8338255b7e33 | DataStax Studio

Now I want to do one task "Python code to insert a new video into the database" as per lab.

I tried this code and getting error:

>>> session.execute(
... "INSERT INTO videos_by_tag (tag, added_date, video_id, title)" +
... "VALUES ('cassandra', '2013-01-10', uuid(), 'Cassandra Is My Friend')")

Traceback (most recent call last):
File "<stdin>", line 3, in <module>
File "cassandra/cluster.py", line 2618, in cassandra.cluster.Session.execute
File "cassandra/cluster.py", line 4877, in cassandra.cluster.ResponseFuture.result
cassandra.InvalidRequest: Error from server: code=2200 [Invalid query] message="Type error: cannot assign result of function system.uuid (type uuid) to video_id (type timeuuid)"
>>>

I tried below but failed:

  1. UUIDs.timeBased()

ERROR:

cassandra.InvalidRequest: Error from server: code=2200 [Invalid query] message="Unknown function uuids.timebased called"
  1. cassandra.util.uuid_from_time

ERROR:

cassandra.protocol.SyntaxException: <Error from server: code=2000 [Syntax error in CQL query] message="line 1:109 no viable alternative at input '.' (...)VALUES ('cassandra', '2013-01-10', [cassandra].util...)">

For time being I have hardcoded the value.

session.execute(
... "INSERT INTO videos_by_tag (tag, added_date, video_id, title)" +
... "VALUES ('cassandra', '2013-01-10', 245e8024-14bd-11e5-9743-8238357b7e32, 'Cassandra Is My Friend')")

Success in DB:

cassandra | 2013-01-10 00:00:00.000000+0000 | 245e8024-14bd-11e5-9743-8238357b7e32 | Cassandra Is My Friend

But I want to know this ?


Solution

  • You are correct in that the call to the uuid() function is your problem:

    INSERT INTO videos_by_tag (tag,added_date,video_id,title)
    VALUES ('cassandra', '2013-01-10', uuid(), 'Cassandra Is My Friend');
    

    The uuid() function generates a type-4 UUID, whereas the video_id column is defined as a type-1 UUID (aka a TIMEUUID).

    Instead, invoke the now() function to get a TIMEUUID:

    INSERT INTO videos_by_tag (tag,added_date,video_id,title)
    VALUES ('cassandra', '2013-01-10', now(), 'Cassandra Is My Friend');