Cassandra - 查询具有集合类型的列

Roh*_*hit 9 cassandra

我对 cassandra 很陌生,所以如果这被证明是一个愚蠢的问题,请原谅我。

我有一个表结构如下

CREATE TABLE data_points (
  id text PRIMARY KEY,
  created_at timestamp,
  previous_event_id varchar,
  properties map<text,text>
);
Run Code Online (Sandbox Code Playgroud)

我想知道,我是否可以执行从map类型字段中提供匹配记录的查询。

例如,如果我在表中插入值如下

INSERT INTO datapoints (id, properties) VALUES ('1', { 'fruit' : 'apple', 'band' : 'Beatles' });
Run Code Online (Sandbox Code Playgroud)

我能把它作为

SELECT * from data_points WHERE properties.band='Beatles';

请帮忙。

小智 17

您可以在cassandra 2.1及更高版本中索引集合类型。你在追求:
SELECT * FROM <table> WHERE <field> CONTAINS <value_in_list/map/set>

详细示例:

cqlsh> USE ks;
cqlsh:ks> CREATE TABLE data_points (
            id text PRIMARY KEY,
            created_at timestamp,
            previous_event_id varchar,
            properties map<text,text>
         );
cqlsh:ks> create index on data_points (properties);
cqlsh:ks> INSERT INTO data_points (id, properties) VALUES ('1', { 'fruit' : 'apple', 'band' : 'Beatles' });
cqlsh:ks> INSERT INTO data_points (id, properties) VALUES ('2', { 'fruit' : 'cherry', 'band' : 'Beatles' });
cqlsh:ks> SELECT * FROM data_points WHERE properties CONTAINS 'Beatles';

 id | created_at | previous_event_id | properties
----+------------+-------------------+----------------------------------------
  2 |       null |              null | {'band': 'Beatles', 'fruit': 'cherry'}
  1 |       null |              null |  {'band': 'Beatles', 'fruit': 'apple'}

(2 rows)
Run Code Online (Sandbox Code Playgroud)

警告的话,二级索引不能很好地扩展,因为它们使用分散/收集算法来查找您需要的内容,如果您打算使用它们进行大量标记,最好将properties字段非规范化为一个单独的表并执行多个查询。

进一步阅读: