Inserting JSON data into a table in Cassandra
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_id | company | first_name | last_name |
---|---|---|---|
102aa90a-4bba-211f-a4fb-00002a102cda | abc | Ayush | NA |
101aa90a-4bba-211f-a4fb-00001a101cda | abc | Ashish | Rana |
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_id | company | first_name | last_name |
---|---|---|---|
104aa90a-4bba-211f-a4fb-00001a101cda | null | Ashish | Rana |
103aa90a-4bba-211f-a4fb-00001a101cda | abc | Ashish | Rana |
102aa90a-4bba-211f-a4fb-00002a102cda | abc | Ayush | NA |
101aa90a-4bba-211f-a4fb-00001a101cda | abc | Ashish | Rana |
Contact Us