| The Cassandra 1.2 documentation is transitioning to a new format! Please use the new Cassandra 1.2 documentation instead. | Back to Table of Contents All Documents List |
This release of Cassandra includes collection types, introduced earlier in this document, that provide an improved way of handling tasks, such as building multiple email address capability into tables.
You can expire each element of a collection by setting an individual time-to-live (TTL) property, as shown in Setting Expiration.
A set stores a group of elements that are returned in sorted order when queried. A column of type set consists of unordered unique values. Using the set data type, you can solve the multiple email problem in an intuitive way that does not require a read before adding a new email address. For example, you can define an emails set in the users table to accommodate multiple email address:
CREATE TABLE users (
user_id text PRIMARY KEY,
first_name text,
last_name text,
emails set<text>
);
To insert data into the set, enclose values in curly brackets. Set values must be unique. For example:
INSERT INTO users (user_id, first_name, last_name, emails)
VALUES('frodo', 'Frodo', 'Baggins', {'f@baggins.com', 'baggins@gmail.com'});
To add an element to a set, use the UPDATE command and the addition (+) operator:
UPDATE users
SET emails = emails + {'fb@friendsofmordor.org'} WHERE user_id = 'frodo';
To remove an element from a set, use the subtraction (-) operator.
UPDATE users
SET emails = emails - {'fb@friendsofmordor.org'} WHERE user_id = 'frodo';
When you query a table containing a collection, Cassandra retrieves the collection in its entirety; consequently, keep collections small enough to be manageable, or construct a data model to replace collections that can accommodate large amounts of data.
To return the set of email belonging to frodo, for example:
SELECT user_id, emails FROM users WHERE user_id = 'frodo';
Cassandra returns results in an order based on the type of the elements in the collection. For example, a set of text elements is returned in alphabetical order.
user_id | emails
---------+-------------------------------------------------------------------
frodo | {"baggins@caramail.com","f@baggins.com","fb@friendsofmordor.org"}
If you want elements of the collection returned in insertion order, use a list.
To remove all elements from a set, you can use the UPDATE or DELETE statement:
UPDATE users SET emails = {} WHERE user_id = 'frodo';
DELETE emails FROM users WHERE user_id = 'frodo';
A set, list, or map needs to have at least one element; otherwise, Cassandra cannot distinguish the set from a null value.
SELECT user_id, emails FROM users WHERE user_id = 'frodo';
user_id | emails
---------+------------------------------------------------
frodo | null