How to auto generate uuid in cassandra CQL 3 command line

后端 未结 4 1474
名媛妹妹
名媛妹妹 2020-12-25 11:14

Just learning cassandra, is there a way to insert a UUID using CQL, ie

create table stuff (uid uuid primary key, name varchar);
insert into stuff (name) valu         


        
相关标签:
4条回答
  • 2020-12-25 11:26

    As of Cassandra 2.0.7 you can just use uuid(), which generates a random type 4 UUID:

    INSERT INTO users(uid, name) VALUES(uuid(), 'my name');
    
    0 讨论(0)
  • 2020-12-25 11:37

    You can with time uuids (type 1 UUID) using the now() function e.g.

    insert into stuff (uid, name) values(now(), 'my name');
    

    Works with uid or timeuuid. It generates a "guaranteed unique" UID value, which also contains the timestamp so is sortable by time.

    There isn't such a function for type 4 UUIDs though.


    UPDATE: This note pertains to older versions of Cassandra. For newer versions, see below.

    0 讨论(0)
  • 2020-12-25 11:41

    Actually there is a way to do that using the blob conversion functions - blobAsType() and typeAsBlob(). In your case this should be:

    insert into stuff (uid, name) values(blobAsUuid(timeuuidAsBlob(now())), 'my name');
    

    This converts timeuuid to blob and from the blob converts it to uuid.

    0 讨论(0)
  • 2020-12-25 11:42

    A UUID is a Universally Unique ID used to avoid collisions.

    Cassandra 2.0.7 and later versions include the uuid() function that takes no parameters and generates a Type 4 UUID for use in INSERT or SET statements.

    You can also use a timeuuid type with a function like now(). They generate a Type 1 UUID.

    The difference between Type 1 and Type 4 UUIDs is that a Type 1 UUID is generated using a timestamp and a Type 4 is generated using random numbers.

    If you want to use a timeuuid as a uuid use something like blobAsUuid(timeuuidAsBlob(now())), since the value returned by now() is guaranteed to be unique.

    References:

    http://docs.datastax.com/en/cql/3.3/cql/cql_reference/uuid_type_r.html

    http://docs.datastax.com/en/cql/3.3/cql/cql_reference/timeuuid_functions_r.html

    http://docs.datastax.com/en/cql/3.3/cql/cql_reference/blob_r.html

    0 讨论(0)
提交回复
热议问题