【问题标题】:Cassandra - CqlEngine - using collectionCassandra - CqlEngine - 使用集合
【发布时间】:2013-08-17 20:56:52
【问题描述】:

我想知道如何在 cqlengine 中使用集合 我可以将值插入列表,但只能插入一个值,因此我无法将某些值附加到列表中 我想做这个: 在 CQL3 中:

UPDATE users
SET top_places = [ 'the shire' ] + top_places WHERE user_id = 'frodo';

在 CqlEngine 中:

connection.setup(['127.0.0.1:9160'])
TestModel.create(id=1,field1 = [2])

此代码会将 2 添加到我的列表中,但是当我插入新值时,它会替换为列表中的旧值。

Cqlengine 中唯一的帮助: https://cqlengine.readthedocs.org/en/latest/topics/columns.html#collection-type-columns

我想知道如何通过 cqlengine 读取集合字段。 它是我的 django 项目中的字典吗?怎么用?!!

请帮忙。 谢谢

【问题讨论】:

    标签: collections cassandra cql


    【解决方案1】:

    看看你的例子,它是一个列表。

    给定一个基于 Cassandra CQL 文档的表格:

    CREATE TABLE plays (
        id text PRIMARY KEY,
        game text,
        players int,
        scores list<int>
    )
    

    你必须像这样声明模型:

    class Plays(Model):
            id = columns.Text(primary_key=True)
            game = columns.Text()
            players = columns.Integer()
            scores = columns.List(columns.Integer())
    

    您可以像这样创建一个新条目(省略如何连接的代码):

    Plays.create(id = '123-afde', game = 'quake', players = 3, scores = [1, 2, 3])
    

    然后更新分数列表:

    play = Plays.objects.filter(id = '123-afde').get()
    play.scores.append(20) # <- this will add a new entry at the end of the list
    play.save()            # <- this will propagate the update to Cassandra - don't forget it
    

    现在,如果您使用 CQL 客户端查询数据,您应该会看到新值:

     id       | game  | players | scores
    ----------+-------+---------+---------------
     123-afde | quake |       3 | [1, 2, 3, 20]
    

    要在 python 中获取值,您可以简单地使用数组的索引:

    print "Length is %(len)s and 3rd element is %(val)d" %\
     { "len" : len(play.scores), "val": play.scores[2] }
    

    【讨论】:

    • 非常感谢,所以我们应该将记录读入内存,然后向其中添加一些新值。谢谢,这非常有用,我希望 cqlengine 可以在内部支持它(无需在内存中读取和执行),因为 cql3 可以做到。
    • “盲目更新”cqlengine.readthedocs.org/en/latest/topics/… 支持通过%ATTRIBUTE%__%COMMAND%(两个下划线)功能在服务器端合并集合更改。
    猜你喜欢
    • 1970-01-01
    • 2019-01-13
    • 2021-02-06
    • 2019-06-01
    • 1970-01-01
    • 2014-04-13
    • 2013-09-28
    • 1970-01-01
    • 2016-08-13
    相关资源
    最近更新 更多