Skip to content
A dgraph client driver written in rust ⛺
Branch: master
Clone or download
Pull request Compare This branch is 3 commits behind Swoorup:master.
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Type Name Latest commit message Commit time
Failed to load latest commit information.

A rust client for dgraph

Build Status

Dgraph Rust client which communicates with the server using gRPC.

Before using this client, it is highly recommended to go through and to understand how to run and work with Dgraph.

Table of contents


Dgraph-rs is available on Add the following dependency to your Cargo.toml

dgraph = "0.1.1"

Using a client

Create a client

Dgraph object can be initialised by passing it a list of dgraph::DgraphClient clients as a vector. Connecting to multiple Dgraph servers in the same cluster allows for better distribution of workload. The library provides a macro to do so.

The following code snippet shows just one connection.

let dgraph = make_dgraph!(dgraph::new_dgraph_client("localhost:9080"));

Alternatively, secure client can be used:

fn open_cert_file(path: &str) -> Vec<u8> {

let root_ca = open_cert_file("./tls/ca.crt");
let cert = open_cert_file("./tls/client.user.crt");
let private_key = open_cert_file("./tls/client.user.key");

let dgraph = make_dgraph!(dgraph::new_secure_dgraph_client(

Alter the database

To set the schema, create an instance of dgraph::Operation and use the Alter endpoint.

let op = dgraph::Operation{
  Schema: "name: string @index(exact) .", ..Default::default()
let result = dgraph.alter(&op);
// Check error

Operation contains other fields as well, including DropAttr and DropAll. DropAll is useful if you wish to discard all the data, and start from a clean slate, without bringing the instance down. DropAttr is used to drop all the data related to a predicate.

Create a transaction

To create a transaction, call dgraph.new_txn(), which returns a dgraph::Txn object. This operation incurs no network overhead.

Once dgraph::Txn goes out of scope, txn.discard() is automatically called via the Drop trait. Calling txn.discard() after txn.commit() is a no-op and calling this multiple times has no additional side-effects.

let txn = dgraph.new_txn();

Run a mutation

txn.mutate(mu) runs a mutation. It takes in a dgraph::Mutation object. You can set the data using JSON or RDF N-Quad format.

We define a Person struct to represent a Person and marshal an instance of it to use with Mutation object.

#[derive(Serialize, Deserialize, Default, Debug)]
struct Person {
  uid: String,
  name: String,

let p = Person {
  uid:  "_:alice".to_string(),
  Name: "Alice".to_string(),

let pb = serde_json::to_vec(&p).expect("Invalid json");

let mut mu = dgraph::Mutation {
  json: pb, ..Default::default()

let assigned = txn.mutate(mu).expect("failed to create data");

For a more complete example, see the simple example simple (or the same example with secure client).

Sometimes, you only want to commit a mutation, without querying anything further. In such cases, you can use mu.commit_now = true to indicate that the mutation must be immediately committed.

Run a query

You can run a query by calling txn.query(q). You will need to pass in a GraphQL+- query string. If you want to pass an additional map of any variables that you might want to set in the query, call txn.query_with_vars(q, vars) with the variables map as third argument.

Let's run the following query with a variable $a:

let q = r#"query all($a: string) {
    all(func: eq(name, $a)) {

let mut vars = HashMap::new();
vars.insert("$a".to_string(), "Alice".to_string());

let resp = dgraph.new_readonly_txn().query_with_vars(q, vars).expect("query");
let root: Root = serde_json::from_slice(&resp.json).expect("parsing");
println!("Root: {:#?}", root);

When running a schema query, the schema response is found in the Schema field of dgraph::Response.

let q = r#"schema(pred: [name]) {

let resp = txn.query(q)?;
println!("{:#?}", resp.schema);

Commit a transaction

A transaction can be committed using the txn.commit() method. If your transaction consisted solely of calls to txn.query or txn.query_with_vars, and no calls to txn.mutate, then calling txn.commit is not necessary.

An error will be returned if other transactions running concurrently modify the same data that was modified in this transaction. It is up to the user to retry transactions when they fail.

let txn = dgraph.new_txn();
// Perform some queries and mutations.

let res = txn.commit();
if res.is_err() {
  // Retry or handle error

Integration tests

Tests require Dgraph running on localhost:19080. For the convenience there's docker-compose.yml prepared in the root directory:

docker-compose up -d

Since we are working with database tests also need to be run in a single thread to prevent aborts:

cargo test -- --test-threads=1


Contribution are welcomed. Feel free to raise an issue, for feature requests, bug fixes and improvements.

If you have made changes to the src/proto/api.proto file, you need need to regenerate the source files generated by Protocol Buffer tools. To do that, install the Protocol Buffer Compiler and then run the following command:

cargo run --features="compile-protobufs" --bin protoc
You can’t perform that action at this time.