Let’s start exploring DGraph – Mutations using JSON

This blog will be aimed towards making the readers aware of how to mutate data in DGraph using the most common data format, JSON. Before diving into the blog, you guys must have basic knowledge and understanding of DGraph – what it is and how to get started with it. I have already written a blog on that as well, which you will be able to find here.

Mutation

In DGraph, mutation is understood as performing any change to the data stored in it, be it creating, updating or deleting. The part where the data is read is known as Query in DGraph. So, as you guys might already be aware of, DGraph supports mutating data using RDF Triplets or JSON. In this blog, I will focus on mutating data using JSONFrom here on out I will assume you guys have DGraph up and running on your local machine. If not, then please refer to the blog mentioned in the introduction.

Mutating one node using JSON

Suppose we have data related to books, and currently our database is empty. First of all, we want to insert one book in our database, let’s say the book is the timeless classic The DaVinci Code. For mutating, first, we will have to define our schema, which would look something like –

<genre>: [string] @index(exact) .
<name>: string @index(exact) .
<price>: float @index(float) .
<serNo>: string @index(exact) .

The above schema basically suggests that our book will have a name, serial number(serNo), a price and a list of genres. You don’t need to worry about the schema right now, as that will be part of another blog. For now, you just need to know that these are the properties we are going to have for our book. So now, let’s create a book in our database! The mutation JSON will look something like –

{
  "set": [{
    "name": "The DaVinci Code",
    "serNo": "1",
    "price": 1500.00,
    "genre": ["Mystery", "Thriller", "Detective fiction", "Crime Fiction", "Conspiracy fiction"]
  }]
}

After running the above mutation, you will probably want to verify what you just mutated. For that, we will run a query to get the data that we just inserted. Since we don’t yet know how to query our database using GraphQL+/-, just copy paste the query below to get the results –

{
  getBookByName(func: eq(name, "The DaVinci Code")) {
    name
    serNo
    price
    genre
    uid
  }
}

You are probably wondering what the heck is this uid. This is just a unique hexadecimal that DGraph generates and manages on its own for each and every node it creates. This will later be used to reference an existing node in mutation.

Once the above query is run, you will be able to see the result of the mutation. Now, we will also need to mutate an author who actually wrote this book. So, let us create the author in the database as well, and attach it to this book.

Mutation referencing existing node

For this, we would need some additional predicates, for which we would need to update our schema with something like below –

<dateOfBirth>: dateTime .
<nationality>: string .
<writtenBy>: uid .

After adding the above predicates, we will be ready to mutate an author in our database and attach it to the one book we have in our database, with a JSON mutation looking something like (don’t run this mutation just yet, read on to the next paragraph first!) –

{
  "set": [{
    "uid": "0x54010",
    "writtenBy": {
    "name": "Dan Brown",
    "dateOfBirth": "1964-06-22",
    "nationality": "American",
    "genre": ["Thriller", "adventure", "mystery", "conspiracy"]
    }
  }]
}

After running the above mutation, you will have created a node for the author, and have successfully connected it to the book you created previously, using the writtenBy edge. Let’s first breakdown the above mutation into understandable parts.

  1. The above mutation consists of a uid with the value 0x54010, what the heck is this? This is the uid of the node containing the information of the previously created book. But this uid was given by my dgraph instance running on my local machine, this might be different for you guys. This value is used to identify an already existing node so that connections of new data can be made to an already existing node, or the node can be updated. So, basically how a primary key is used in a relational database to update a row. You will be able to retrieve this value using the above query that I had mentioned here, the uid of that query is the uid of the book that you will want to use here to attach the author to.
  2. Once you have mentioned the node uid, dgraph knows what node you are talking about. So now, we add an edge writtenBy on the book node, since a book has to be written by an author. The writtenBy here in the JSON is an object, signifying dgraph that this is an edge. For DGraph, every object in JSON is a node. Every node has a uid predicate on it. Every edge goes from node to node, making it of type uid. So, in JSON we have assigned the value of writtenBy as an object. This tells DGraph that writtenBy is an edge. So, even if we do not define the schema for it, DGraph will automatically be able to infer that information from the JSON.
  3. In the writtenBy object, we have simply given all the information related to the author.

After replacing the uid in the above mutation with your own book’s uid, you can run the above mutation and verify the result using the below query –

{
  getBookByName(func: eq(name, "The DaVinci Code")) {
    name
    serNo
    price
    genre
    uid
    writtenBy {
      name
      dateOfBirth
      nationality
      genre
      uid
    }
  }
}

This will return the result of the previous as well as the current mutation that we just did.

Mutation referencing a node being created in the same mutation

Now, I want to add two books in my database, with their authors, which happen to be the same in this particular case. I can achieve this in one mutation using a mutation that looks something like –

{
  "set": [{
    "uid": "_:author",
    "name": "Chetan Bhagat",
    "dateOfBirth": "1974-04-22",
    "nationality": "Indian",
    "genre": ["Erotica", "romance","realistic fiction", "non-fiction"]
  }, {
    "name": "Five Point Someone",
    "serNo": "2",
    "price": 228.00,
    "genre": ["Humour", "Fiction"],
    "writtenBy": {
      "uid": "_:author"
    }
  }, {
    "name": "One Indian girl",
    "serNo": "3",
    "price": 110.00,
    "genre": ["Romance novel", "Fiction"],
    "writtenBy": {
      "uid": "_:author"
    }
  }]
}

In the above mutation, we have assigned a variable to the author, using the uid predicate of the node. DGraph provides you with the facility of referencing a node that is yet to be created, by assigning a variable name to the uid predicate of the node you want to refer by using the syntax – _:variableName and then use this value anywhere in your mutation to refer to this node. The special syntax here is the underscore + colon part, that tells dgraph to use this variable name to refer this node elsewhere.

To retrieve the above mutated data, we will quickly update the schema making writtenBy edge as a reverse edge, using something like –

<writtenBy>: uid @reverse .

And then query our database using the below query –

{
  getBooksByAuthor(func: eq(name, "Chetan Bhagat")) {
    name
      dateOfBirth
      nationality
      genre
      uid
    ~writtenBy {
      name
    serNo
    price
    genre
    uid
    }
  }
}

The above query will return the data we just mutated, or, books written by Chetan Bhagat.

This is all there is to mutating data using JSON in DGraph. I hope this blog was useful for you guys and you got to learn something from this. Hope to see you in my next blog. Till then, happy blogging!

 


knoldus-advt-sticker

Written by 

Akshansh Jain is a Software Consultant having more than 1 year of experience. He is familiar with Java but also has knowledge of various other programming languages such as scala, HTML and C++. He is also familiar with different Web Technologies and Android programming. He is a passionate programmer and always eager to learn new technologies & apply them in respective projects.

Leave a Reply

Knoldus Pune Careers - Hiring Freshers

Get a head start on your career at Knoldus. Join us!