Create a table
After the keyspace exists, you can create a table by executing mutations. For this example, two tables are created:
# create two tables (book, reader) in library with a single mutation
# DATA TYPES: TEXT, UUID, SET(TEXT), TUPLE(TEXT, INT, DATE), LIST(UDT)
mutation createTables {
book: createTable(
keyspaceName:"library",
tableName:"book",
partitionKeys: [ # The keys required to access your data
{ name: "title", type: {basic: TEXT} }
]
clusteringKeys: [
{ name: "author", type: {basic: TEXT} }
]
)
reader: createTable(
keyspaceName:"library",
tableName:"reader",
partitionKeys: [
{ name: "name", type: {basic: TEXT} }
]
clusteringKeys: [ # Secondary key used to access values within the partition
{ name: "user_id", type: {basic: UUID}, order: "ASC" }
]
values: [
{ name: "birthdate", type: {basic: DATE} }
{ name: "email", type: {basic: SET, info:{ subTypes: [ { basic: TEXT } ] } } }
{ name: "reviews", type: {basic: TUPLE, info: { subTypes: [ { basic: TEXT }, { basic: INT }, { basic: DATE } ] } } }
{ name: "addresses", type: { basic: LIST, info: { subTypes: [ { basic: UDT, info: { name: "address_type", frozen: true } } ] } } }
]
)
}
"data": {
"book": true,
"reader": true
}
}
It is worth noting that one mutation is used to create two tables. Information about partition keys and clustering keys can be found in the CQL reference.
The second table, reader
, also defines a column using a
user-defined type (UDT).
IF NOT EXISTS option
A table can be created with an option ifNotExists
that will only create the
table if it does not already exist:
# create two tables, magazine and article, IF THEY DON'T EXIST
# DATA TYPES: TEXT, INT, LIST(TEXT)
mutation createTableIfNotExists {
magazine: createTable(
keyspaceName:"library",
tableName:"magazine",
partitionKeys: [ # The keys required to access your data
{ name: "title", type: {basic: TEXT} }
]
clusteringKeys: [ # Secondary key used to access values within the partition
{ name: "pub_yr", type: {basic: INT}, order: "ASC" }
{ name: "pub_mon", type: {basic: INT} }
{ name: "mag_id", type: {basic: INT} }
],
ifNotExists: true,
values: [ # The values associated with the keys
{ name: "editor", type: {basic: TEXT} }
]
)
article: createTable(
keyspaceName:"library",
tableName:"article",
partitionKeys: [ # The keys required to access your data
{ name: "title", type: {basic: TEXT} }
]
clusteringKeys: [ # Secondary key used to access values within the partition
{ name: "mtitle", type: {basic: TEXT} }
],
ifNotExists: true,
values: [ # The values associated with the keys
{ name: "authors", type: {basic:LIST, info:{ subTypes: [ { basic: TEXT } ] } } }
]
)
}
{
"data": {
"magazine": true,
"article": true
}
}
One of these tables includes creating a column with the data type LIST
, an
ordered collection of text values.