cassandra 存储list数组
demo如下:
CREATE TABLE users3 ( user_id text PRIMARY KEY, first_name text, last_name text, emails list<text> ); INSERT INTO users3 (user_id, first_name, last_name, emails) VALUES('frodo', 'Frodo', 'Baggins', ['f@baggins.com', 'baggins@gmail.com']); UPDATE users3 SET emails = emails + ['fb@friendsofmordor.org'] WHERE user_id = 'frodo'; SELECT user_id, emails FROM users3 WHERE user_id = 'frodo';
python代码如下:
from cassandra.cluster import Cluster cluster = Cluster(["10.178.209.161"]) session = cluster.connect('my_keyspace') s = session try: s.execute("CREATE TABLE list_test (a ascii PRIMARY KEY, b list<blob>)") except: pass params = ['key1', [bytearray(b'blob1'), bytearray(b'hello world')]] s.execute("INSERT INTO list_test (a, b) VALUES (%s, %s)", params) results = s.execute("SELECT * FROM list_test") print "********************" for x in results: print x.a, x.b
Collection type
A collection column is declared using the collection type, followed by another type, such as int
or text
, in angle brackets. For example, you can create a table having a list of textual elements, a list of integers, or a list of some other element types.
list<text>
list<int>
Collection types cannot be nested, but frozen collection types can be nested inside frozen or non-frozen collections. For example, you may define a list within a list, provided the inner list is frozen:
list<frozen <list<int>>>
Indexes may be created on a collection column of any type.
A frozen value serializes multiple components into a single value. Non-frozen types allow updates to individual fields. Cassandra treats the value of a frozen type as a blob. The entire value must be overwritten.
column_name collection_type<data_type, frozen<column_name>>
For example:
CREATE TABLE mykeyspace.users (
id uuid PRIMARY KEY,
name frozen <fullname>,
direct_reports set<frozen <fullname>>, // a collection set
addresses map<text, frozen <address>> // a collection map
score set<frozen <set<int>>> // a set with a nested frozen set
);
list的话针对下面的{}修改为[]即可!
Using the set type
A set stores a group of elements that are returned in sorted order when queried. A column of type set consists of unordered unique values. Using the set data type, you can solve the multiple email problem in an intuitive way that does not require a read before adding a new email address.