旧版本的 Cassandra 没有架构,这意味着您没有任何地方可以定义行可以包含的内容。您现在需要的可以部分在 Cassandra 2.1 上使用 Map 完成
CREATE TABLE toys (
id text PRIMARY KEY,
toy map<text, text>
)
放一些数据...
INSERT INTO toys (id, toy) VALUES ( '1', {'name':'Car', 'number_of_doors':'4', 'likes':'3'});
INSERT INTO toys (id, toy) VALUES ( '2', {'type':'Plane', 'flying_range':'100m'});
INSERT INTO toys (id, toy) VALUES ( '3', {'category':'Train', 'number_of_carriages':'10'});
表格内容...
id | toy
----+-------------------------------------------------------
3 | {'category': 'Train', 'number_of_carriages': '10'}
2 | {'flying_range': '100m', 'type': 'Plane'}
1 | {'likes': '3', 'name': 'Car', 'number_of_doors': '4'}
我们现在可以在键上创建索引...
CREATE INDEX toy_idx ON toys (KEYS(toy));
...并对 Map 键执行查询 ...
SELECT * FROM toys WHERE toy CONTAINS KEY 'name';
id | toy
----+-------------------------------------------------------
1 | {'likes': '3', 'name': 'Car', 'number_of_doors': '4'}
现在您可以像处理普通列一样更新或删除地图条目,而无需在写入前读取
DELETE toy['name'] FROM toys WHERE id='1';
UPDATE toys set toy = toy + {'name': 'anewcar'} WHERE id = '1';
SELECT * FROM toys;
id | toy
----+-----------------------------------------------------------
3 | {'category': 'Train', 'number_of_carriages': '10'}
2 | {'flying_range': '100m', 'type': 'Plane'}
1 | {'likes': '3', 'name': 'anewcar', 'number_of_doors': '4'}
一些限制
- 您无法检索集合的一部分:即使内部地图的每个条目都存储为列,您也只能检索整个集合
- 您必须选择是同时为键还是值创建索引
不支持。
- 由于输入了地图,因此您不能放置混合值 - 在我的示例中,所有整数现在都是字符串
我个人认为这种方法的广泛使用是一种反模式。
HTH,
卡罗