在cassandra DB

时间:2016-02-18 16:13:24

标签: python mongodb dictionary cassandra nosql

我有一个带有键空间的cassandra数据库,如下所示:

CREATE TABLE custumer_events_service.events(
    acceptFirstContactDuration decimal,
    currentTime timestamp,
    visitorIdentifier text,
    PRIMARY KEY (visitorIdentifier, currentTime)
) WITH CLUSTERING ORDER BY (currentTime DESC);

和一个python dict

{u'acceptFirstContactDuration': 0,
 u'currentTime': u'2016-02-18T11:51:55.468Z',
 u'12eca72928845aae26268f431b8c75b2564d7919c916e',}

有没有办法直接用cassandra-driver插入此dict?我正在寻找类似于mongodb的东西

>>> import datetime
>>> post = {"author": "Mike",
...         "text": "My first blog post!",
...         "tags": ["mongodb", "python", "pymongo"],
...         "date": datetime.datetime.utcnow()}

>>> posts = db.posts
>>> post_id = posts.insert_one(post).inserted_id

1 个答案:

答案 0 :(得分:3)

您可以手动构建一个CQL插入语句,迭代字典中的键和值,但cqlengine Model可能比dict更适合使用,而且很容易使用Model

中的值填充dict

您可以像这样定义Model(使用所有列扩展它):

class CustomerEventsServiceEvent(Model):
    __table_name__ = "customer_events_service.events"

    acceptFirstContactDuration = columns.Decimal()
    allSeenPageCount = columns.Decimal()
    callAcceptedCount = columns.Decimal()

如果d是字典变量的名称,那么

event = CustomerEventsServiceEvent(**d)
event.save()

等同于您的MongoDB操作。