“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:
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.
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:
id int,
cve_reports cve_reports,
primary key(id)
);
Insert Data
We can then fetch the added data as:
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!!