User-Defined Data Type
Discover User-Defined Types (UDTs) which allow developers to define custom data types, enabling the compact representation of related data by organizing it within a single column.
The following diagram illustrates the various categories of data types offered by Apache Cassandra.
User-defined types (UDTs)
Apache Cassandra provides users the ability to define custom data types called User Defined Types or UDTs, enabling flexible and efficient data modeling.
A UDT groups multiple related fields together and allows embedding complex data within a single column. UDT fields have a name and data type which could be a native data type/collection/another UDT.
The CREATE TYPE
statement
A UDT
is created with the CREATE TYPE
statement, very similar to the CREATE TABLE
statement, as shown below:
CREATE TYPE [IF NOT EXISTS] [keyspaceName.]UDT_name (field_name cql_type,field_name cql_type,...);
Please refer to syntax conventions for CQL syntax notation details.
Each UDT
must have a name listed after the CREATE TYPE
clause. The fields of the UDT
are listed enclosed in parenthesis. A UDT
can contain multiple fields, each with a unique name. The data type for a field may be native, collection, or another UDT.
If the container keyspace has not been selected with the USE keyspace
statement prior to issuing the CREATE TYPE
command, or to create the UDT
in a different keyspace, the desired keyspace may be specified before the UDT
name with the following syntax
CREATE TYPE keyspaceName.UDT_name(...
If the UDT
already exists in the keyspace, the CREATE TYPE
statement results in error. This error can be avoided and the CREATE TYPE
statement made a no-op with the inclusion of IF NOT EXISTS
directive.
CREATE TYPE IF NOT EXISTS UDT_name(...
Let’s assume we wish to capture instructor details. The following UDT
will capture the instructor’s full name:
CREATE TYPE fullnameUDT(title text,first_name text,last_name text);
The above statement defines a UDT
titled fullnameUDT
with three text fields: title
, first_name
, and last_name
. Similarly, the following UDT
will be used to store the instructor’s qualification(s):
CREATE TYPE qualificationUDT (degree TEXT,institution TEXT,completion_year INT);
The above statement defines a UDT
titled qualificationUDT
with three fields representing the degree obtained, the institution where it was completed, and the year of completion.
Once UDTs
have been created, they can be used as data types in tables, functions, and other UDTs
.
The DESCRIBE TYPES
statement
The DESCRIBE TYPES
command lists all user-defined types (UDTs
) in the specified/current keyspace. ...