在Python中为Cassandra生成UUID

10 投票
2 回答
4772 浏览
提问于 2025-04-16 01:14

嘿,

我正在使用

cf.insert(uuid.uuid1().bytes_le, {'column1': 'val1'}) (pycassa)

来为Cassandra创建一个TimeUUID,但遇到了这个错误:

InvalidRequestException: 
InvalidRequestException(why='UUIDs must be exactly 16 bytes')

它在

uuid.uuid1()
uuid.uuid1().bytes
str(uuid.uuid1())

时也不管用。

有什么好的方法可以创建一个有效的TimeUUID,以便与CompareWith="TimeUUIDType"这个标志一起使用吗?

谢谢,
Henrik

2 个回答

9

看起来你是把uuid当作行的标识,而不是列的名称。

这个compare_with: TimeUUIDType属性是用来说明列名的比较方式,意思是它会使用TimeUUIDType来进行比较,也就是它告诉Cassandra在进行切片操作时,如何对进行排序

你有没有考虑过使用一些高级的Python客户端呢?比如说TradedgyLazy BoyTelephus或者Pycassa

4

你需要确保你的列族(column family)结构可以接受UUID作为键。你的代码将会在这样创建的列族中正常工作(使用cassandra-cli):

create column family MyColumnFamily
  with column_type = 'Standard'
  and comparator = 'AsciiType'
  and default_validation_class = 'BytesType'
  and key_validation_class = 'TimeUUIDType';

要向这个列族中添加值,可以使用:

import pycassa
pool = pycassa.ConnectionPool('Keyspace1')
cf = pycassa.ColumnFamily(pool, 'MyColumnFamily')
cf.insert(uuid.uuid1(), {'column1': 'val1'})

撰写回答