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.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」