Insert a dict in cassandra DB

2019-07-08 02:37发布

I have a cassandra database with a keyspace that looks like:

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

And a python dict

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

Is there a way to insert this dict directly with cassandra-driver? I am looking for something like in 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条回答
对你真心纯属浪费
2楼-- · 2019-07-08 03:21

You could manually construct a CQL insert statement iterating over the keys and values in the dictionary, but a cqlengine Model is probably more appropriate to use than a dict, and it is easy to populate a Model with the values from the dict.

You can define the Model like so (extending it with all of your columns):

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

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

If d is the name of your dictionary variable, then

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

is the equivalent of your MongoDB operation.

查看更多
登录 后发表回答