Reputation: 50362
Can a primary key in Cassandra contain a collection column?
Example:
CREATE TABLE person (
first_name text,
emails set<text>,
description text
PRIMARY KEY (first_name, emails)
);
Upvotes: 13
Views: 6929
Reputation: 318
It's been a while but as this is on first page in Google when you look for using a map in the primary key, I thought it was worth to update it.
Cassandra now allows (I think since 2.1) to use a collection in a Primary Key provided it is frozen.
A frozen value serializes multiple components into a single value. Non-frozen types allow updates to individual fields. Cassandra treats the value of a frozen type as a blob. The entire value must be overwritten.
With frozen, the collection becomes essentially immutable not allowing for modifications in-place, therefore, becoming suitable for a Primary Key.
Here is an example using a frozen list.
CREATE TABLE test_frozen (
app_id varchar,
kind varchar,
properties frozen <list<text>>,
PRIMARY KEY ((app_id, kind), properties));
Since 2.1, Cassandra also allows to create an index on columns of type map, set or list - though that not's necessarily a good idea.
Upvotes: 14
Reputation: 132862
Collection types cannot be part of the primary key, and neither can the counter type. You can easily test this yourself, but the reason might not be obvious.
Sets, list, maps are hacks on top of the storage model (but I don’t mean that in a negative way). A set is really just a number of columns with the same key prefix. To be a part of the primary key the value must be scalar, and the collection types aren’t.
Upvotes: 17
Reputation: 236004
I'd say no: because the collection is mutable, and you can't have a primary key that keeps changing in time.
Upvotes: 7