Open In App

Secondary Indexes on SET Collection in Cassandra

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will discuss the overview of Secondary Indexes on SET Collection in Cassandra and then will implement the exercise and will see how it actually works, and then finally will conclude the importance of Secondary Indexes on SET Collection. Let’s discuss it one by one.

Pre-requisite –

Overview :
Creating secondary Indexes on SET Collection in Cassandra is very useful. So, here you will see the real use case of creating an index on a collection because it makes searching and querying data very efficient and fast. So if, you want to search based on a keyword then while searching and querying data, you can use the CONTAINS keywords for a specific keyword in the collection data type. Let’s understand the whole concept with the help of examples.

Syntax :
In this, you will see the syntax part of how to create an index on collection. You can use the given below command as follows.

CREATE INDEX ON <table_name>(<collection_column>)

Here, you will see the syntax of the WHERE clause part where you will use the CONTAINS keyword to search the specific value in the SET collection. 

WHERE <collection_column> CONTAINS <value>

Example –
Let’s consider you have existing keyspace namely cluster1 and then first we will create a user_data table by using the CQL command as follows.

Step-1: Creating table -user_data –

use cluster1;
create table user_data
           (
           user_id varchar,
           user_first_name varchar,
           user_last_name varchar,
           company varchar,
           user_tags set<varchar>,
           primary key(user_id)
           );

Step-2: Creating Index on user_tags –

CREATE INDEX ON user_data(user_tags);

Step-3: Inserting data –

insert into user_data(user_id, user_first_name, user_last_name, company, user_tags) 
values('Ashish01','Ashish','Rana','abc',{'Java'});

insert into user_data(user_id, user_first_name, user_last_name, company, user_tags) 
values('Ashish02','Ayush','NA','abc',{'Python'});

insert into user_data(user_id, user_first_name, user_last_name, company, user_tags) 
values('Ashish03','shivang','NA','abc',{'python'});

insert into user_data(user_id, user_first_name, user_last_name, company, user_tags) 
values('Ashish04','Bhagyesh','NA','abc',{'c++'});

Step-4: Verifying and Reading data – 

select * from user_data;

Step-5: Output – 

user_id company user_first_name user_last_name user_tags
Ashish04 abc Bhagyesh  NA {‘c++’}
Ashish03 abc shivang  NA {‘python’}
Ashish02 abc Ayush  NA {‘Python’}
Ashish01 abc Ashish  Rana {‘Java’}

Step-6: Searching on the basis of specific keyword – 

select * from user_data where user_tags CONTAINS 'Java';

Step-7: Output –

user_id company user_first_name user_last_name user_tags
Ashish01 abc Ashish  Rana {‘Java’}

 


Last Updated : 17 Mar, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads