范围查询是一个棘手的问题。
执行实范围查询的方法是使用复合主键,将范围放在聚类部分上。由于范围位于集群部分,因此您无法执行您编写的查询:你至少需要在整个分区键上有一个相等的条件。
让我们看一个例子:
CREATE TABLE users (
mainland text,
state text,
uid int,
name text,
zip int,
PRIMARY KEY ((mainland), state, uid)
)
uid 现在是一个 int 只是为了让测试更容易
insert into users (mainland, state, uid, name, zip) VALUES ( 'northamerica', 'washington', 1, 'john', 98100);
insert into users (mainland, state, uid, name, zip) VALUES ( 'northamerica', 'texas', 2, 'lukas', 75000);
insert into users (mainland, state, uid, name, zip) VALUES ( 'northamerica', 'delaware', 3, 'henry', 19904);
insert into users (mainland, state, uid, name, zip) VALUES ( 'northamerica', 'delaware', 4, 'dawson', 19910);
insert into users (mainland, state, uid, name, zip) VALUES ( 'centraleurope', 'italy', 5, 'fabio', 20150);
insert into users (mainland, state, uid, name, zip) VALUES ( 'southamerica', 'argentina', 6, 'alex', 10840);
现在查询可以执行您需要的操作:
select * from users where mainland = 'northamerica' and state > 'ca' and state < 'ny';
Output
mainland | state | uid | name | zip
-------------+----------+-----+--------+-------
northamerica | delaware | 3 | henry | 19904
northamerica | delaware | 4 | dawson | 19910
如果将 int (age, zipcode) 作为聚类键的第一列,则可以执行比较整数的相同查询。
小心:大多数人在看到这种情况时开始思考“好吧,我可以放置一个始终相同的假分区键,然后我可以执行范围查询”。这是一个巨大的错误,分区键负责跨节点的数据分布。设置修复分区键意味着所有数据将在同一节点(及其副本)中完成。
将世界区域划分为 15/20 区域(为了拥有 15/20 分区键)是可以的,但这还不够,只是为了创建一个有效的示例。
编辑:由于问题的编辑
我并没有说这是唯一的可能性;如果您找不到有效的方法来分区users并且需要执行这种查询,这是一种可能性,而不是唯一的一种。应在聚类关键部分上执行范围查询。 AGE 作为分区键的一个弱点是您无法对其执行 UPDATE,任何时候您需要更新用户的年龄时,您都必须执行删除和插入(另一种方法可以是写入birth_year/birth_date 而不是年龄,然后计算客户端)
回答你关于添加二级索引的问题:实际上二级索引的查询不支持IN运算符。从 CQL 消息来看,他们似乎很快就会开发它
错误请求:非主键列 (xxx) 上的 IN 谓词尚未
支持的
然而,即使二级索引支持 IN 运算符,您的查询也不会改变
select * from users where age IN (15,16,17,....30)
只是为了澄清我的概念:任何没有“干净”和“就绪”解决方案的东西都需要用户努力以满足其需求的方式对数据进行建模。举个例子(我并不是说这是一个好的解决方案:我不会使用它)
CREATE TABLE users (
years_range text,
age int,
uid int,
PRIMARY KEY ((years_range), age, uid)
)
放一些数据
insert into users (years_range, age , uid) VALUES ( '11_15', 14, 1);
insert into users (years_range, age , uid) VALUES ( '26_30', 28, 3);
insert into users (years_range, age , uid) VALUES ( '16_20', 16, 2);
insert into users (years_range, age , uid) VALUES ( '26_30', 29, 4);
insert into users (years_range, age , uid) VALUES ( '41_45', 41, 5);
insert into users (years_range, age , uid) VALUES ( '21_25', 23, 5);
查询数据
select * from users where years_range in('11_15', '16_20', '21_25', '26_30') and age > 14 and age < 29;
output
years_range | age | uid
-------------+-----+-----
16_20 | 16 | 2
21_25 | 23 | 5
26_30 | 28 | 3
此解决方案可能会解决您的问题,并且可以在小型集群中使用,其中大约 20 个键 (0_5 ...106_110) 可能具有良好的分布。但这一解决方案与之前的解决方案一样,不允许更新并减少了密钥的分发。优点是 IN 集较小。
在 S.I. 已经允许 IN 子句的完美世界中,我将使用 UUID 作为分区键,将years_range(设置为birth_year_range)作为 S.I. 并“过滤”我的数据客户端(如果对 10 > 年龄 > 22 感兴趣,我会要求IN('1991_1995', '1996_2000', '2001_2005', '2006_2010', '2011_2015')
计算并删除我的申请中无用的年份)
哈特哈,
卡洛