本文介绍cassandra支持的,目前我所知道的所有查询表达式类型。如果你需要更复杂的查询,单单依靠cassandra是很难做到的,你需要借助其它手段或者工具。 cassandra目前支持的表达式目前有三种: 我们先假设我们的表结构是这样的:
create table test(
a int,
b int,
c int,
d int,
e int,
primary key(a,b,c,d)
);
create index on test(e);
1、前缀表达式 就是查询条件必须是主键,且前面的主键是=号,只有最后一个主键是> >= < <=。 举例:
select * from test where a=1 and b>2;
select * from test where a=1 and b=1 and c>2;
select * from test where a=1 and b=1 and c=1 and d>2;
select * from test where a=1 and b=1 and c>2 and c<2;
以上都是可行的。
select * from test where a>1;
//不行,第一主键只能用=号
select * from test where a=1 and c>2;
//不行 中间不能有跳跃
select * from test where a=1 and b>2 and b>=2;
//不行,同一个主键不能同时用> >= = 或者< <= =
2、不含第一主键的前缀表达式
这类表达式,需要加上ALLOW FILTERING来查询,这样的查询效率肯定是低一些
举例:
select * from test where b>2 ALLOW FILTERING;
select * from test where b=1 and c>2 ALLOW FILTERING;
select * from test where b=1 and c=1 and d>2 ALLOW FILTERING;
select * from test where b=1 and c>2 and c<2 ALLOW FILTERING;
3、包含索引列查询
举例:
select * from test where e=1;
//只含索引
select * from test where a=1 and b=1 and c>1 and e=1;
//包含索引列和前缀表达式的组合
select * from test where b=1 and c>1 and e=1;
//包含索引列和不含第一主键的前缀表达式的组合 不需要ALLOW FILTERING
select * from test where c>1 and e=1 ALLOW FILTERING;
//除此之外和任意其它表达式的组合,都可以进行查询,
//前提是要加ALLOW FILTERING;
最后说一下,cassandra查询出来的结果,无论什么查询结果,都是先按token(a)排序,再按b排序 再按c排序,再按d排序:
a | b | c | d | e
---+---+---+---+---
13 | 2 | 3 | 4 | 5
1 | 2 | 1 | 4 | 5
1 | 2 | 3 | 1 | 5
1 | 2 | 3 | 2 | 5
1 | 2 | 3 | 4 | 5
1 | 2 | 3 | 7 | 5
1 | 2 | 6 | 4 | 5
1 | 3 | 2 | 4 | 5
1 | 4 | 3 | 7 | 5
1 | 7 | 3 | 7 | 5
2 | 2 | 3 | 4 | 5
21 | 2 | 3 | 4 | 5
这有助你进行分页查询