当尝试选择使用where条件时,"错误请求:PRIMARY KEY部分to_id不能被限制"

Thi*_*oyd 3 cql cassandra cqlsh

这是我的cassandra表,用于聊天类应用程序:

CREATE TABLE tax_keyspace_dev.chat_messages (
  message text,
  when timestamp,
  from_id text,
  to_id text,
  read boolean,
  participants text,
  PRIMARY KEY(participants, when, to_id)
);
Run Code Online (Sandbox Code Playgroud)

此查询工作:

select * from tax_keyspace_dev.chat_messages where participants='caone@one.com_shashank_shrivastava@acme.com' order by when;
Run Code Online (Sandbox Code Playgroud)

但是以下查询不起作用:

select * from tax_keyspace_dev.chat_messages where to_id='caone@one.com' order by when; 
Run Code Online (Sandbox Code Playgroud)

错误是" 错误请求:PRIMARY KEY部分to_id不能被限制(前一部分不受限制或非EQ关系) "

update tax_keyspace_dev.chat_messages set read=true where participants = 'caone@one.com_shashank_shrivastava@acme.com' and when = '2014-04-10 17:44:22+0530'; 
Run Code Online (Sandbox Code Playgroud)

错误是" 错误请求:缺少必需的PRIMARY KEY部分to_id "

如果我从复合键中删除"to_id"并创建单独的索引,如下所示:

CREATE TABLE tax_keyspace_dev.chat_messages (
 message text,
 when timestamp,
 from_id text,
 to_id text,
 read boolean,
 participants text,
 PRIMARY KEY(participants, when)
);
CREATE INDEX idx_chat_messages_to ON tax_keyspace_dev.chat_messages (to_id);
Run Code Online (Sandbox Code Playgroud)

然后其他查询工作,但这一次失败:

select * from tax_keyspace_dev.chat_messages where to_id='caone@one.com' order by when;
Run Code Online (Sandbox Code Playgroud)

错误" 错误请求:不支持使用第二个索引的ORDER BY. "

如何设计我的表以便所有这些用例都可以工作?

select * from tax_keyspace_dev.chat_messages where participants='caone@one.com_shashank_shrivastava@acme.com' order by when;
update tax_keyspace_dev.chat_messages set read=true where participants = 'caone@one.com_shashank_shrivastava@acme.com' and when = '2014-04-10 17:44:22+0530';
select * from tax_keyspace_dev.chat_messages where to_id='caone@one.com' order by when;
Run Code Online (Sandbox Code Playgroud)

Ana*_*nth 5

使用cassandra时,主键的第一部分将成为分区键.因此,要转到特定分区以检索行,您需要始终使用equals约束指定主键.

select * from tax_keyspace_dev.chat_messages where participants='caone@one.com_shashank_shrivastava@acme.com' order by when;
Run Code Online (Sandbox Code Playgroud)

以下查询建议您到达名为"参与者"的行分区,然后在使用ASC的默认排序时按顺序排序.由于您的列默认按升序排序,因此可能也不需要此顺序.

select * from tax_keyspace_dev.chat_messages where to_id='caone@one.com' order by when; 

select * from tax_keyspace_dev.chat_messages where to_id='caone@one.com' order by when;
Run Code Online (Sandbox Code Playgroud)

以下查询不起作用,因为您没有提供行分区来定位值.默认情况下,行分区键用于标识包含数据的SSTable.因此,默认情况下,cassandra不支持这种代价高昂的操作.

发生的事情很简单.如果您错过了这个行分区键,cassandra必须扫描所有SSTable并从中获取数据.这可以通过使用ALLOW FILTERING来完成,但是您的查询会变得昂贵,因为它不会使用bloom过滤器.

update tax_keyspace_dev.chat_messages set read=true where participants = 'caone@one.com_shashank_shrivastava@acme.com' and when = '2014-04-10 17:44:22+0530'; 
Run Code Online (Sandbox Code Playgroud)

如果cassandra更新,它与插入没有什么不同.只考虑使用地图进行操作的情况.您正在尝试修改值,但您没有完整的地图键.在内部,cassandra存储的值是"participant_when_to_id":value.