2013-08-16 26 views
4

我想知道如何使用cqlengine中的集合 我可以將值插入列表中,但只有一個值,因此我無法在列表中添加一些值 我想這樣做: 在CQL3:Cassandra - CqlEngine - 使用集合

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項目中的字典嗎?我如何使用它?!

請幫忙。 謝謝

回答

2

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

給出了基於卡桑德拉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] } 
+0

非常感謝,所以我們應該把記錄讀到內存然後給它添加一些新的值。感謝這是非常有用的,我希望cqlengine可以在內部支持它(不需要在內存中讀取和執行),因爲cql3可以做到這一點。 –

+0

「盲目更新」https://cqlengine.readthedocs.org/en/latest/topics/queryset.html#blind-updates支持服務器端通過'%ATTRIBUTE%__%COMMAND%'合併收集更改(兩個下劃線)特徵。 – ddotsenko