Skip to content
Related Articles

Related Articles

Improve Article
Inserting JSON data into a table in Cassandra
  • Difficulty Level : Basic
  • Last Updated : 17 Mar, 2021

In this article, you will be able to understand how you can insert JSON data into a table in Cassandra and will discuss with the help of an example and then finally conclude the importance of JSON insertion. Let’s discuss it one by one.

Overview :
It is a practical way than cqlsh to insert column and column values. In JSON values inserted in the form of string if they are not a number for example id with datatype uuid inserted as a string but will be stored as uuid. For better understanding now, first, we will see insertion data using cqlsh commands and then will discuss how you can insert data by using JSON format. 

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.

use cluster1;
create table user_record
           (
           user_id uuid,
           first_name varchar,
           last_name varchar,
           company varchar,
           primary key(user_id)
           );

Method-1 : 
Insertion by using cqlsh commands –

insert into user_record(user_id, first_name, last_name, company) 
values(101aa90a-4bba-211f-a4fb-00001a101cda,'Ashish','Rana','abc');

insert into user_record(user_id, first_name, last_name, company) 
values(102aa90a-4bba-211f-a4fb-00002a102cda,'Ayush','NA','abc');

After insertion, you can use the following cql command to verify the inserted data.



select * from user_record;

Output –

user_idcompanyfirst_namelast_name
102aa90a-4bba-211f-a4fb-00002a102cdaabc AyushNA
101aa90a-4bba-211f-a4fb-00001a101cdaabcAshishRana

Method-2 :
Insertion by using JSON format –
To insert data in JSON format, JSON keyword will be added to the INSERT command as follows. 

 INSERT INTO cluster1.user_record JSON '{
 "user_id" : "103aa90a-4bba-211f-a4fb-00001a101cda",  
 "first_name" : "Ashish",  
 "last_name" : "Rana",
 "company" : "abc" }';

 Using JSON format if you do not insert any value for any column then a null value will be entered automatically as you can see in the below given example.

 INSERT INTO cluster1.user_record JSON '{
 "user_id" : "104aa90a-4bba-211f-a4fb-00001a101cda",  
 "first_name" : "Ashish",  
 "last_name" : "Rana" 
 }';

After insertion, you can use the following cql command to verify the inserted data.

select * from user_record;

Output –

user_idcompanyfirst_namelast_name
104aa90a-4bba-211f-a4fb-00001a101cdanullAshishRana
103aa90a-4bba-211f-a4fb-00001a101cda abc  Ashish Rana
102aa90a-4bba-211f-a4fb-00002a102cdaabc AyushNA
101aa90a-4bba-211f-a4fb-00001a101cdaabcAshishRana

Attention reader! Don’t stop learning now. Get hold of all the important CS Theory concepts for SDE interviews with the CS Theory Course at a student-friendly price and become industry ready.

 

My Personal Notes arrow_drop_up
Recommended Articles
Page :