Set Type in Cassandra - Cassandra / CQL Tutorial

Set Type in Cassandra

Set type in Cassandra is used to store group of elements with unique values. If you try to save the duplicate values in set, it is not going to save those duplicate values distinctly. The data is stored without order but when you select the data , the output is displayed as sorted.

Let's create a table with Set type, I am storing the names of children of a parent in set type. When we create table we have to provide the data type of elements in set e.g Set<Text> or Set<Int>.

CQLSH:techbrotherstutorials>CREATE TABLE tbs 
             ( 
                          id INT PRIMARY KEY, 
                          parentname TEXT, 
                          childrenSET<text> 
             );

 

Let's insert data into table which has column of Set Type.

 CQLSH:techbrotherstutorials>INSERT INTO tbs 
            ( 
                        id, 
                        parentname, 
                        children 
            ) 
            VALUES 
            ( 
                        1, 
                        'Aamir', 
                        {'Raza', 'Rida', 'Najaf', 'Haider'} 
            );

 

Check the data by using Select query in CQL, Noticed that in above insert query we inserted data un sorted but below you can see the it is displayed as sorted data.

CQLSH:techbrotherstutorials>SELECT * 
FROM   tbs;

If you will try to insert duplicate elements values, they will be saved as single value. See that I have "Raza" twice in my elements in below insert query.

CQLSH:techbrotherstutorials>INSERT INTO tbs 
            ( 
                        id, 
                        parentname, 
                        children 
            ) 
            VALUES 
            ( 
                        2, 
                        'Shahzad', 
                        {'Raza', 'Rida', 'Najaf', 'Haider', 'Raza'} 
            );

Check the data in table by using Select query in CQL, Noticed that there is only single "Raza" value saved.