cassandra的索引查询和排序

cassandra的查询虽然很弱,但是它也是支持索引和排序的,当然是简陋的查询,这一切都是为了追求性能的代价,所以要使用cassandra,你不能希望它完全适用你的逻辑,而是把你的逻辑设计的更适合cassandra。

第一:索引查询 cassandra是支持创建二级索引的,索引可以创建在除了第一个主键之外所有的列上,当然有些类型除外,例如集合类型。 例如

create table test(
	a int,
	b int,
	c int,
	d int,
	e int,
	m int,
	primary key(a,b,c));

create index on test(c);
create index on test(e);

在第一主键a上创建索引是不可以的:

create index on test(a) X

索引列只可以用=号查询,所以

select * from test where e=1; //是可以
select * from test where e>1; //就不行了。

如果你的查询条件里,有一个是根据索引查询,那其它非索引非主键字段,可以通过加一个ALLOW FILTERING来过滤实现、 例如:

select * from test where e=1 and m>2 ALLOW FILTERING;

虽然m字段是非索引非主键字段,但是只要加了ALLOW FILTERING条件,它会先根据e=1查出来,再对结果进行m>2过滤

第二:排序 cassandra也是支持排序的,order by。 当然它的排序也是有条件的, 第一:必须有第一主键的=号查询。cassandra的第一主键是决定记录分布在哪台机器上,也就是说cassandra只支持单台机器上的记录排序。 第二:那就是只能根据第二、三、四…主键进行有序的,相同的排序。 第三:不能有索引查询

select * from test where a=1 ORDER BY b desc;
select * from test where a=1 ORDER BY b desc, c desc;
select * from test where a=1 ORDER BY b asc;
select * from test where a=1 ORDER BY b asc, c asc;

以上都是可以的。

select * from test ORDER BY b desc; //没有第一主键 不行
select * from test where a=1 ORDER BY c desc; //必须以第二主键开始排序
select * from test where a=1 ORDER BY b desc, c asc; //不是相同的排序。
select * from test where e=1 ORDER BY b desc; //不能有索引。

其实cassandra的任何查询,最后的结果都是有序的,默认的是b asc, c asc,因为它内部就是这样存储的。 这个我在《cassandra2.0 如何实现分页查询》文章中提到过。所以你使用b desc, c asc 或者b asc,c desc 去排序,cassandra是比较为难的。 当然这个默认存储排序方式,是可以在建表的时候指定的。

create table test(
	a int,
	b int,
	c int,
	d int,
	e int,
	m int,
	primary key(a,b,c))
WITH CLUSTERING ORDER BY (b desc, c asc);