Upsert Mutations
Upsert mutations allow you to perform add
or update
operations based on whether a particular ID exists in the database
We’re overhauling Dgraph’s docs to make them clearer and more approachable. If you notice any issues during this transition or have suggestions, please let us know.
Upsert mutations allow you to perform add
or update
operations based on
whether a particular ID
exists in the database. The IDs must be external IDs,
defined using the @id
directive in the schema.
For example, to demonstrate how upserts work in GraphQL, take the following schema:
Schema
Dgraph automatically generates input and return types in the schema for the
add
mutation, as shown below:
Suppose you want to update the text
field of a post with the ID mm2
. But you
also want to create a new post with that ID in case it doesn’t already exist. To
do this, you use the addPost
mutation, but with an additional input variable
upsert
.
This is a Boolean
variable. Setting it to true
results in an upsert
operation.
It performs an update
mutation and carry out the changes you specify in your
request if the particular ID exists. Otherwise, it falls back to a default add
operation and create a new Post
with that ID and the details you provide.
Setting upsert
to false
is the same as using a plain add
operation—it’ll
either fail or succeed, depending on whether the ID exists or not.
Example: add mutation with upsert
true:
With variables:
If a post with the ID mm2
exists, it updates the post with the new details.
Otherwise, it’ll create a new Post
with that ID and the values you provided.
In either case, you’ll get the following response back:
upsert
is false
.The current behavior of Add
and Update
mutations is such that they don’t
update deep level nodes. So Add mutations with upsert
set to true
only
updates values at the root level.
Examples
You can refer to the following link for more examples.
Was this page helpful?