Cassandra Collections: Set, List & Map in CQL with Example

What are Cassandra Collections?

Cassandra collections are a good way for handling tasks. Multiple elements can be stored in collections. There are limitations in Cassandra collections.

  • Cassandra collection cannot store data more than 64KB.
  • Keep a collection small to prevent the overhead of querying collection because entire collection needs to be traversed.
  • If you store more than 64 KB data in the collection, only 64 KB will be able to query, it will result in loss of data.

Types of Cassandra Collections

There are mainly three types of collections that Cassandra supports:

  1. Set
  2. List
  3. Map

Cassandra Set Collection

A Set stores group of elements that returns sorted elements when querying.

Syntax

Here is the syntax of the Set collection that store multiple email addresses for the teacher.

Create table University.Teacher
(
id int,
Name text,
Email set<text>,
Primary key(id)
);

Example

Here is the snapshot where table “Teacher” is created with “Email” column as a collection.

Example of Cassandra Set Collection

Here is the snapshot where data is being inserted in the collection.

Example of Cassandra Set Collection

insert into University.Teacher(id,Name,Email) values(l,'Guru99',{'abc@gmail.com','xyz@hotmail.com'});

Cassandra List Collection

When the order of elements matters, the list is used.

Example

Here is the snapshot where column courses of list type id added in table “Teacher.”

Example of Cassandra List Collection

Here is the snapshot where data is being inserted in column “coursenames”.

Example of Cassandra List Collection

insert into University.Teacher(id,Name,Email) values(2,'Hamilton',{'hamilton@hotmail.com'},[Data Science']);

Here is the snapshot that shows the current database state after insertion.

Cassandra List Collection Example

Cassandra Map Collection

The map is a collection type that is used to store key value pairs. As its name implies that it maps one thing to another.

For example, if you want to save course name with its prerequisite course name, map collection can be used.

Example

Here is the snapshot where map type is created for course name and its prerequisite course name.

Example of Cassandra Map Collection

Here is the snapshot where data is being inserted in map collection type.

Example of Cassandra Map Collection

insert into University.Course(id,prereq) values(1,{'DataScience':'Database', 'Neural Network':'Artificial Intelligence'});

Summary

  • Cassandra collections are a good way for handling tasks. Multiple elements can be stored in collections.
  • There are mainly three types of collections in Cassandra: Set, List, and Map
  • A Set collection stores group of elements that returns sorted elements when querying.
  • The List collection is used when the order of elements matters.
  • The Map is a collection type that is used to store key value pairs.