Apache Cassandra

Cassandra Create Type

“Cassandra allows us to define custom types that can hold related information in a table. If you cannot find a type to hold your type of data, you can use built-in types to define another type that captures your desired layout.

It is good to keep in mind that the defined type is limited to the scope of the keyspace on which its created. You can use the dot notation to access a table from another keypspace.

This post will discuss how you can define a user type using the CREATE TYPE command.”

Create Type Command Syntax

The following command depicts the syntax of the create type command:

CREATE TYPE [IF NOT EXISTS]
keyspace_name.type_name(
field_name cassandra_type[,]
[field_name cassandra_type] [,...]
);

 
The command supports the IF EXISTS clause, which allows you to quash errors if the command with a similar name exists in the target type.

Type_name must include a unique name that conforms to Cassandra’s naming rules.

Finally, you can define the fields for your type and their respective CQL type. Do not use counter fields in custom types.

Example

The following example shows how to define a custom type that holds CVE reports.

drop keyspace if exists zero_day;

create keyspace zero_day
with replication = {
    'class': 'SimpleStrategy',
    'replication_factor': 1
};
use zero_day;

create type cve_reports (
    cve_number text,
    report_date date,
    affected_vendor text,
    severity float,
);

 
The query above starts by creating a keyspace “zero_day” which will hold the defined user type.

You will notice that the create type statement follows a similar format to table creation. Although this is true, they serve a different purposes, and one can be a better choice than the other.

NOTE: Consider the performance implications before choosing a table over a custom type and vice versa.

We can then insert data into the table above as shown:

We can create a table with the cve_reports type and insert sample data as shown:

create table records(
    id int,
    cve_reports cve_reports,
    primary key(id)
);

 

Insert Data

 

insert into records(id, cve_reports) values (1, {cve_number: 'CVE-2021-33852', report_date: '2022-12-02', affected_vendor: 'WordPress', severity: 6.0});

 
We can then fetch the added data as:

select * from records;

 

Resulting Output

 

Conclusion

This post covered the basics of creating and using custom-defined types in Apache Cassandra. We also discussed how to create a table with custom types and insert data into a custom type column.

Happy coding!!

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list