如何使用Cassandra DB对次要索引使用(排序)

时间:2018-09-29 11:15:58

标签: cassandra

我的表架构是:

CREATE TABLE users
(user_id BIGINT PRIMARY KEY, 
user_name text, 
email_ text);

我在表格的下面插入了行。

INSERT INTO users(user_id, email_, user_name)
VALUES(1, 'abc@test.com', 'ABC');

INSERT INTO users(user_id, email_, user_name)
VALUES(2, 'abc@test.com', 'ZYX ABC');

INSERT INTO users(user_id, email_, user_name)
VALUES(3, 'abc@test.com', 'Test ABC');

INSERT INTO users(user_id, email_, user_name)
VALUES(4, 'abc@test.com', 'C ABC');

为了将数据搜索到user_name列中,我创建了一个索引,以将LIKE运算符与'%%'一起使用:

CREATE CUSTOM INDEX  idx_users_user_name ON users (user_name)
USING 'org.apache.cassandra.index.sasi.SASIIndex'
WITH OPTIONS = {
'mode': 'CONTAINS',
'analyzer_class': 'org.apache.cassandra.index.sasi.analyzer.NonTokenizingAnalyzer', 
'case_sensitive': 'false'};

问题:1 当我在Query下方执行时,它仅返回3条记录,而不是4条记录。

select * 
from users 
where user_name like '%ABC%';

问题:2 当我使用下面的查询时,它给出了错误

ERROR: com.datastax.driver.core.exceptions.InvalidQueryException: 
ORDER BY with 2ndary indexes is not supported. 
Query =select * from users where user_name like '%ABC%' ORDER BY user_name ASC;

查询:

select * 
from users 
where user_name like '%ABC%' 
ORDER BY user_name ASC;

我的要求是用user_name过滤order by user_name

1 个答案:

答案 0 :(得分:1)

The first query does work correctly for me using cassandra:latest which is now cassandra:3.11.3. You might want to double-check the inserted data (or just recreate from scratch using the cql statements you provided).

The second one gives you enough info - ordering by secondary indexes is not possible in Cassandra. You might have to sort the result set in your application.

That being said I would not recommend running this setup in real apps. With some additional scale (when you have many records) this will be a suicide performance-wise. I should not go into much detail since maybe you already understand this and SO is not a wikia/documentation site, so here is a link之后,按钮字体颜色错误。