Cassandra简述
依赖
由于项目中使用的spring boot版本较低,Cassandra的版本选为1.5.6.RELEASE。引入依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-cassandra</artifactId> <version>1.5.6.RELEASE</version> </dependency>该依赖又依赖于guava,补充:
<dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>19.0</version> </dependency>主键
Cassandra在使用联合主键时,第一主键是parition key, 决定了数据的分区,后面的主键是**Clustering Key,**决定了数据在分区中的排序方式。
排序
Cassandra只能在分区里进行排序,且默认是Clustering Key升序排列,如果有多个Clustering Key,则排序优先级依次下降。
新增表的时候,可以使用 with clustering order by(Clustering Key)来决定数据在分区中以何种方式排序。这样查出来的数据默认就是指定的排序方式,不用使用order by。
Cassandra的排序支持较弱,所以应该在设计主键的时候就确定好数据在分区内的排序方式,而不是显示在cql里指定。
查询
Cassandra对查询有很多限制。
查询条件不支持 IN OR
第一主键、索引列仅支持 = 查询,Clustering Key需配合主键(主键等于某个确定的值),才能进行= > >= < <= 四种查询,单独作为条件不可行。
当查询条件不满足上述条件,但因业务需要查询时,可在查询语句最后添加allow filtering。可能有性能问题,未进行性能分析。
查询视图时,就算视图的原表对应的字段加了索引,也必须加上allow filtering
分页
不支持offset。目前处理业务分页时,将0到limit的数据全查出来,在java程序里手动分页。页面需去掉跳转页面以及最后一页功能。
新增
批量新增时,有大小限制。默认上限为50kb,超过上限需分批次更新
# Fail any batch exceeding this value. 50kb (10x warn threshold) by default. batch_size_fail_threshold_in_kb: 50api
可配合Spring Data Repositories使用。在查询需要添加allow filtering的时候会出现问题。目前业务多用 cassandra-template 相关api