问题
I want to execute this query on a cassandra table:
select query,score,term from mytable where term
like '%bottle%' order by score desc limit 10;
The only columns of the table are query, score, term.
I create the table as follows:
CREATE TABLE mytable( "term" TEXT, "query" TEXT, "score" double,
PRIMARY KEY ("term","score")) WITH CLUSTERING ORDER BY (score desc);
I also have an index:
This gives all sort of crazy errors. The first is:
InvalidRequest: code=2200 [Invalid query] message="LIKE restriction is
only supported on properly indexed columns. term LIKE 'bottle' is not valid."
If I replace the LIKE with equals, the query works. But I need the LIKE and the order by. So, after some googling, I thought I would use a SASI index.
CREATE CUSTOM INDEX term_idx2 ON mytable (term) USING
'org.apache.cassandra.index.sasi.SASIIndex' WITH OPTIONS = {
'analyzer_class':
'org.apache.cassandra.index.sasi.analyzer.StandardAnalyzer',
'case_sensitive': 'false'};
This produces another error message:
InvalidRequest: code=2200 [Invalid query] message=
"Cannot create secondary index on partition key column term"
OK. This maybe means that if I want to use LIKE, I should not create a secondary index on "term". Then let's try to query by "query" instead. The query becomes:
select query,score,term from mytable where query
like '%bottle%' order by score desc limit 10;
Now, this produces the "use ALLOW FILTERING" error. Essentially leading me to create index on query. Even creating the SASI type index on query does not not help.
Is this at all possible?
回答1:
No! you can't use all like and order by in same query.
You already know you can't create indexes on primary and clustering keys. However, you can create indexes on other columns e.g: query
, by using following command:
CREATE CUSTOM INDEX mytable_query_idx ON mytable ("query")
USING 'org.apache.cassandra.index.sasi.SASIIndex'
WITH OPTIONS = {'mode': 'CONTAINS',
'analyzer_class': 'org.apache.cassandra.index.sasi.analyzer.StandardAnalyzer',
'case_sensitive': 'false'};
And after that, you make a query like
SELECT * FROM mytable WHERE query LIKE '%abc%';
But you can't use order by and like in same query because
"ORDER BY with 2ndary indexes is not supported."
Howerver, If you really need these functionality Cassandra is not a good choice.
来源:https://stackoverflow.com/questions/49247092/order-by-and-like-in-same-cassandra-query