3

Can the Cassandra SELECT DISTINCT operation be used to find all the unique values of a column if that column has an index on it?

My question is not the same as simply asking how to find distinct values of a non primary key columns. I realize that Cassandra does not allow queries that would require a table-scan, because they would be inefficient; here the presence of an index eliminates the need for a table scan.

If I have a table thus:

CREATE TABLE thing (
   id uuid,
   version bigint,
   name text,
   ... data columns ...
   PRIMARY KEY ((id),version)
);
CREATE INDEX ON thing(name);

I can SELECT DISTINCT id FROM thing; to get all the thing IDs. That requires one response from each node in my cluster, with each response returning the keys for its node.

But can I SELECT DISTINCT name FROM thing; to get all the thing names? That should also require only one response from each node in my cluster, with each response constructed only by examining the portion of the index on its node. And if name is a good column on which to have an index, each response would be smaller that the query for the primary keys (there should be fewer names than partition keys).

1 Answer 1

0

At least to me the documentation suggests that I should be able to select distinct values of any column:

DISTINCT selection_list

selection_list is one of:

  • A list of partition keys (used with DISTINCT)
  • selector AS alias, selector AS alias, ...| *

Where selector is column name. The documentation makes no restriction on what column name could be.

Matter of fact, you can only use DISTINCT with partition key columns (C* 2.2.4). Using it on anything else will yield an error:

cqlsh:stresscql> SELECT distinct name FROM thing ;
InvalidRequest: code=2200 [Invalid query] message="SELECT DISTINCT queries must only request partition key columns and/or static columns (not name)"

I don't have any in-depth understanding on the workings of secondary indexes, but I also have the feeling that allowing a DISTINCT count on an indexed column should not be worse in terms of reads incurred than querying the index for a particular value. But as indexed values repeat across nodes it would be worse in terms of memory and network overhead relative to the result size as the coordinator would condense down the nodes' responses to only contain unique values. Though, for replication factors > 1 this is also the case for partition key values.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.