【问题标题】:Python loop inserting last row only in cassandraPython循环仅在cassandra中插入最后一行
【发布时间】:2016-08-15 11:38:21
【问题描述】:

我键入了一个小的演示循环,以便在 Cassandra 中插入随机值,但只有最后一条记录被持久化到数据库中。我正在使用来自 datastax 的 cassandra-driver 及其对象建模库。 Cassandra 版本是 3.7 和 Python 3.4。知道我做错了什么吗?

#!/usr/bin/env python

import datetime
import uuid
from random import randint, uniform
from cassandra.cluster import Cluster
from cassandra.cqlengine import connection, columns
from cassandra.cqlengine.management import sync_table
from cassandra.cqlengine.models import Model
from cassandra.cqlengine.query import BatchQuery

class TestTable(Model):
    _table_name = 'test_table'
    key = columns.UUID(primary_key=True, default=uuid.uuid4())
    type = columns.Integer(index=True)
    value = columns.Float(required=False)
    created_time = columns.DateTime(default=datetime.datetime.now())


def main():
    connection.setup(['127.0.0.1'], 'test', protocol_version = 3)
    sync_table(TestTable)

    for _ in range(10):
        type = randint(1, 3)
        value = uniform(-10, 10)
        row = TestTable.create(type=type, value=value)
        print("Inserted row: ", row.type, row.value)

    print("Done inserting")

    q = TestTable.objects.count()
    print("We have inserted " + str(q) + " rows.")


if __name__ == "__main__":
    main()

非常感谢!

【问题讨论】:

    标签: python cassandra


    【解决方案1】:

    问题出在关键列的定义中:

    key = columns.UUID(primary_key=True, default=uuid.uuid4())
    

    对于默认值,它将调用一次uuid.uuid4 函数并将该结果用作所有未来插入的默认值。因为这是您的主键,所以所有 10 次写入都将发生在同一个主键上。

    相反,请去掉括号,这样您就只是传递了对 uuid.uuid4 的引用,而不是调用它:

    key = columns.UUID(primary_key=True, default=uuid.uuid4)
    

    现在,每次创建行时,您都会获得一个新的唯一 UUID 值,从而在 Cassandra 中获得一个新行。

    【讨论】:

      【解决方案2】:

      你需要使用方法save。

      ...
      row = TestTable(type=type, value=value)
      row.save()
      ...
      

      http://cqlengine.readthedocs.io/en/latest/topics/models.html#cqlengine.models.Model.save

      【讨论】:

      • 谢谢,但一直失败。很奇怪,这两行好像写了两次,也只存了一条记录。
      猜你喜欢
      • 1970-01-01
      • 2014-07-02
      • 2018-04-01
      • 2020-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-16
      • 2015-01-20
      相关资源
      最近更新 更多