上面的示例使用动态单元格(内部列)名称(即 123、456、111、222)。您可以通过使用复合主键在 CQL 中实现这一点:
cqlsh:test> DESC TABLE user_by_item ;
CREATE TABLE test.user_by_item (
item_id int,
user_id int,
user_name text,
PRIMARY KEY (item_id, user_id)
);
cqlsh:test> select * from user_by_item WHERE item_id = 111;
item_id | user_id | user_name
---------+---------+-----------
111 | 123 | Jay
111 | 456 | John
(2 rows)
cqlsh:test> select * from user_by_item WHERE item_id = 111 and user_id = 123;
item_id | user_id | user_name
---------+---------+-----------
111 | 123 | Jay
(1 rows)
cqlsh:test> DESCRIBE TABLE item_by_user ;
CREATE TABLE test.item_by_user (
user_id int,
item_id int,
item_name text,
PRIMARY KEY (user_id, item_id)
);
cqlsh:test> SELECT * from item_by_user WHERE user_id = 123;
user_id | item_id | item_name
---------+---------+-----------
123 | 111 | iphone
123 | 222 | ipad
(2 rows)
cqlsh:test> SELECT * from item_by_user WHERE user_id = 123 and item_id = 111;
user_id | item_id | item_name
---------+---------+-----------
123 | 111 | iphone
(1 rows)
您的主键的第一部分将是您的“内部行键”,第二部分将用作“集群键”,即作为“内部单元格/列”名称的一部分。因此,表格将以与您的示例类似的方式在内部/物理上存储,并且WITH COMPACT STORAGE
选项将为您提供与示例中完全相同的物理布局
看看http://www.datastax.com/dev/blog/thrift-to-cql3和http://thelastpickle.com/blog/2013/01/11/primary-keys-in-cql.html _更多细节。