Tuesday 3 March 2020

Cassandra: Working with set

Set is a collection of elements, which don't permits duplicate elements.

How to create a column of type set?
Use ‘set’ keyword to create a column of type set.
CREATE TABLE IF NOT EXISTS cassandratutorial.person (
  id INT PRIMARY KEY, 
  firstName VARCHAR,
  lastName VARCHAR,
  hobbies SET<VARCHAR>
);

How to insert elements to set?
By placing the elements in {}, you can insert elements to a set.

INSERT INTO cassandratutorial.person  (id, firstName, lastName, hobbies) VALUES (1, 'Hari', 'Krishna', {'football', 'cricket', 'trekking'});
cqlsh> CREATE TABLE IF NOT EXISTS cassandratutorial.person (
   ...   id INT PRIMARY KEY, 
   ...   firstName VARCHAR,
   ...   lastName VARCHAR,
   ...   hobbies SET<VARCHAR>
   ... );
cqlsh> 
cqlsh> INSERT INTO cassandratutorial.person  (id, firstName, lastName, hobbies) VALUES (1, 'Hari', 'Krishna', {'football', 'cricket', 'trekking'});
cqlsh> 
cqlsh> SELECT * FROM cassandratutorial.person;

 id | firstname | hobbies                             | lastname
----+-----------+-------------------------------------+----------
  1 |      Hari | {'cricket', 'football', 'trekking'} |  Krishna

(1 rows)

Add elements to a set
Using + operator, you can add elements to a set.

UPDATE cassandratutorial.person SET hobbies = hobbies + {'tennis', 'blogging'} WHERE id = 1;

cqlsh> UPDATE cassandratutorial.person SET hobbies = hobbies + {'tennis', 'blogging'} WHERE id = 1;
cqlsh> 
cqlsh> SELECT * FROM cassandratutorial.person;

 id | firstname | hobbies                                                   | lastname
----+-----------+-----------------------------------------------------------+----------
  1 |      Hari | {'blogging', 'cricket', 'football', 'tennis', 'trekking'} |  Krishna

(1 rows)

Removing elements from a set
Using – operator, you can remove elements from the set.

cqlsh> UPDATE cassandratutorial.person SET hobbies = hobbies - {'tennis', 'blogging'} WHERE id = 1;
cqlsh> 
cqlsh> SELECT * FROM cassandratutorial.person;

 id | firstname | hobbies                             | lastname
----+-----------+-------------------------------------+----------
  1 |      Hari | {'cricket', 'football', 'trekking'} |  Krishna

(1 rows)




Previous                                                    Next                                                    Home

No comments:

Post a Comment