How to use Dgraph in your java application!!

In this blog, we are going to learn how to interact with Dgraph in your java application. Before we dive into the coding part, we will first have a basic understanding of what we are going to use.

So to make a connection with Dgraph server we need the Dgraph client. The client can communicate with the server in two different ways through gRPC and HTTP.

In this blog, we are going to use the Dgraph client using gRPC. The first step to communicate with the server is to create a client. Now let’s see how to do that.

Creating the Dgraph client

ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost",9080)
                         .usePlaintext(true).build();
DgraphStub stub = DgraphGrpc.newStub(channel);

We have made the ManagedChannel that is used to manage the Channel lifecycle. Dgraph client uses the Stub which is used to perform the GRPC operations. Now that we have made the Dgraph client. We can use it for the Dgraph operations.

What are the operations that we can perform?

We can alter the database, run the mutation or even we can run the query. So one by one we are going to perform everything.

Alter the Database.

To set the schema of the graph we have to create the operations.

String schema = "name: string @index(exact) .";
Operation operation = Operation.newBuilder().setSchema(schema).build();
dgraphClient.alter(operation);

Here, schema variable will have the list of the predicate that we are going to have in our database. We have created the operation object so that we can pass that in the alter method of the Dgraph client. Now our database will have a name predicate.

To perform the mutation or query a Dgraph, we have to make the transaction.

There are two types of transactions :

  • The read-only transaction that is used to query the Dgraph
  • The transaction that is used to perform mutation.

For both types of transaction, we need to create the Transaction object.

Transaction transaction = dgraphClient.newTransaction(); 

Adding data to Dgraph

We have to use the mutation method to mutate the Dgraph.

Person person = new Person();
person.name = "Alice";

// Serialize the person object.
Gson gson = new Gson();
String json = gson.toJson(person);

Adding person data to Dgraph.

Mutation mutation = Mutation.newBuilder() 
              .setSetJson(ByteString.copyFromUtf8(json.toString()))
              .build();
transaction.mutate(mutation);

To make the mutation object, it accepts the serializable object. Here json is a serializable object.

After the mutation is done, we have to commit the transaction.

  transaction.commit();

Reading data from Dgraph

First, we have to prepare the query then we have to create the transaction then call the queryWithVars method that accepts the query and the Map of String.  The map represents the placeholder and their values. What this method does it replaces all the placeholder with the provided value.

String query =
"query all($a: string){\n" + "all(func: eq(age, $agePlaceHolder)) {\n" + " name\n" + " }\n" + "}";
Map vars = Collections.singletonMap("$agePlaceHolder", "24");
try {
Response response = dgraphClient.newTransaction().queryWithVars(query, vars);
// Deserialize
People people = objectMapper.readValue(response.getJson().toByteArray(), People.class);

return people;

Update data in Dgraph

To update data in dgraph we need the uid. Uid is a unique hexadecimal number given to each node that uniquely distinguishes the node.  So if we want to update the node data we need the uid so that it won’t create the new node only update the existing node.

we see through the example:

Person updatePerson = Person.builder().uid(uid).name("Sam").build();
Mutation mutation = Mutation.newBuilder() 
              .setSetJson(ByteString.copyFromUtf8(json.toString()))
              .build();
transaction.mutate(mutation);

In person object, uid is the uid of the person node that we want to update. The name represents the new name by which it should be replaced.

Delete the node in Dgraph

To delete the node in Dgraph you just need the uid of the node to delete the node. It will delete the entire node.

Person deletePerson = Person.builder().uid(uid).build();
Mutation mutation = Mutation.newBuilder() 
              .setDeleteJson(ByteString.copyFromUtf8(json.toString()))
              .build();
transaction.mutate(mutation);

 

You can refer to complete code from GitHub link.

References:

Knoldus-Scala-Spark-Services

Written by 

Priyanka Thakur is a Software Consultant having 6 months of experience currently working at Knoldus Software LLP. She has done MCA at BVICAM, GGSIPU. She has a graduation degree in BCA from JIMS, GGSIPU. She is familiar with programming language' s such as C, Java, and Scala. She also has interest in Angular and Docker and currently working on Logam. She is dedicated, focused and hardworking person. Her interests are in to face new programming challenges because she believes these challenges produce opportunity. She is keen to learn new technologies. In her leisure time, she prefers reading about mythology, watching movies.

Knoldus Pune Careers - Hiring Freshers

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