Insert data
If you have created schema for insertion, now you are ready to write data into the database.
First, let’s navigate to your new keyspace library
inside the playground.
Change the location to
http://localhost:8080/graphql/library
and add a couple of books:
mutation insert2books {
nativeson: insertBook(book: { title: "Native Son", isbn: "978-0061148507", author: ["Richard Wright"] }) {
title
}
mobydick: insertBook(book: { title: "Moby Dick", isbn: "978-1503280786", author: ["Herman Melville"]}) {
title
}
}
{
"data": {
"insertBook": {
"title": "Native Son"
}
}
}
{
"data": {
"insertBook": {
"title": "Moby Dick"
}
}
}
The insertion is straightforward. The title and author are specified, and the title is returned in response to a successful insertion. Only the required fields must be specified, and any fields can be returned in the response. This same operation can update stored data, as insertions are upserts in all cases.
Conditional insertion
type Book @key @cql_entity(name: "book") @cql_input {
title: String! @cql_column(partitionKey: true)
isbn: String @cql_column(clusteringOrder: ASC)
author: [String] @cql_index(name: "author_idx", target: VALUES)
}
type InsertBookResponse @cql_payload {
applied: Boolean!
book: Book!
}
type Mutation {
insertBookIfNotExists(book: BookInput!): InsertBookResponse
}
Insert arrays and UDTs
Inserting arrays and UDTs requires a few extra embellishments:
mutation insert2Readers {
janedoe: insertReader(
reader: {
name: "Jane Doe"
user_id: "f02e2894-db48-4347-8360-34f28f958590"
reviews: [
{
bookTitle: "Moby Dick"
comment: "It's about a whale."
rating: 3
reviewDate: "2021-04-01"
}
{
bookTitle: "Native Son"
comment: "An awesome work of art."
rating: 5
reviewDate: "2021-01-01"
}
]
}
) {
name
user_id
birthdate
email
address {
street
city
state
zipCode
}
}
herman: insertReader(
reader: {
name: "Herman Melville"
user_id: "e0ec47e1-2b46-41ad-961c-70e6de629810"
birthdate: "1900-01-01"
email: ["hermy@mobydick.org", "herman.melville@gmail.com"]
address: {
street: "100 Main St"
city: "Boston"
state: "MA"
zipCode: "50050"
}
}
) {
name
user_id
birthdate
email
address {
street
city
state
zipCode
}
}
}
{
"data": {
"insertReader": {
"name": "Jane Doe",
"user_id": "f02e2894-db48-4347-8360-34f28f958590"
}
}
}
{
"data": {
"insertReader": {
"name": "Herman Melville",
"birthdate": "1900-01-01",
"email": [
"hermy@mobydick.org",
"herman.melville@gmail.com"
],
"address": [
{
"street": "100 Main St",
"city": "Boston",
"state": "MA",
"zipCode": "50050"
}
]
}
}
}
Note the use of square brackets around arrays of objects, with commas separating array items.