dgo GoDoc Build Status

Official Dgraph Go client which communicates with the server using gRPC.

Before using this client, we highly recommend that you go through and to understand how to run and work with Dgraph.

Table of contents


Note that, dgo 1.0.0 works with dgraph 1.0.x only

go get -u -v

Using a client

Create a client

dgraphClient object can be initialised by passing it a list of api.DgraphClient clients as variadic arguments. Connecting to multiple Dgraph servers in the same cluster allows for better distribution of workload.

The following code snippet shows just one connection.

conn, err := grpc.Dial("localhost:9080", grpc.WithInsecure())
if err != nil {
defer conn.Close()
dgraphClient := dgo.NewDgraphClient(api.NewDgraphClient(conn))
Alter the database

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

op := &api.Operation{
  Schema: `name: string @index(exact) .`,
err := dgraphClient.Alter(ctx, 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 dgraphClient.NewTxn(), which returns a *dgo.Txn object. This operation incurs no network overhead.

It is a good practice to call txn.Discard() using a defer statement after it is initialized. Calling txn.Discard() after txn.Commit() is a no-op and you can call txn.Discard() multiple times with no additional side-effects.

txn := dgraphClient.NewTxn()
defer txn.Discard(ctx)

Read-only transactions can be created by calling c.NewReadOnlyTxn(). Read-only transactions are useful to increase read speed because they can circumvent the usual consensus protocol. Read-only transactions cannot contain mutations and trying to call txn.Commit() will result in an error. Calling txn.Discard() will be a no-op.

Run a mutation

txn.Mutate(ctx, mu) runs a mutation. It takes in a context.Context and a *api.Mutation object. You can set the data using JSON or RDF N-Quad format.

To use JSON, use the fields SetJson and DeleteJson, which accept a string representing the nodes to be added or removed respectively (either as a JSON map or a list). To use RDF, use the fields SetNquads and DeleteNquads, which accept a string representing the valid RDF triples (one per line) to added or removed respectively. This protobuf object also contains the Set and Del fields which accept a list of RDF triples that have already been parsed into our internal format. As such, these fields are mainly used internally and users should use the SetNquads and DeleteNquads instead if they are planning on using RDF.

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

type Person struct {
  Uid  string `json:"uid,omitempty"`
  Name string `json:"name,omitempty"`

p := Person{
  Uid:  "_:alice",
  Name: "Alice",

pb, err := json.Marshal(p)
if err != nil {

mu := &api.Mutation{
  SetJson: pb,
assigned, err := txn.Mutate(ctx, mu)
if err != nil {

For a more complete example, see GoDoc.

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

Run a query

You can run a query by calling txn.Query(ctx, 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.QueryWithVars(ctx, q, vars) with the variables map as third argument.

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

q := `query all($a: string) {
    all(func: eq(name, $a)) {

resp, err := txn.QueryWithVars(ctx, q, map[string]string{"$a": "Alice"})

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

q := `schema(pred: [name]) {

resp, err := txn.Query(ctx, q)
Commit a transaction

A transaction can be committed using the txn.Commit(ctx) method. If your transaction consisted solely of calls to txn.Query or txn.QueryWithVars, 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.

txn := dgraphClient.NewTxn()
// Perform some queries and mutations.

err := txn.Commit(ctx)
if err == y.ErrAborted {
  // Retry or handle error
Setting Metadata Headers

Metadata headers such as authentication tokens can be set through the context of gRPC methods. Below is an example of how to set a header named "auth-token".

// The following piece of code shows how one can set metadata with
// auth-token, to allow Alter operation, if the server requires it.
md := metadata.New(nil)
md.Append("auth-token", "the-auth-token-value")
ctx := metadata.NewOutgoingContext(context.Background(), md)
dg.Alter(ctx, &op)


Running tests

Make sure you have dgraph installed before you run the tests. This script will run the unit and integration tests.

go test -v ./...
Expand ▾ Collapse ▴



    Package dgo is used to interact with a Dgraph server. Queries, mutations, and most other types of admin tasks can be run from the client.

    Example (GetSchema)
    Example (SetObject)
    {"me":[{"name":"Alice","dob":"1980-01-01T23:00:00Z","age":26,"loc":{"type":"Point","coordinates":[1.1,2]},"raw_bytes":"cmF3X2J5dGVz","married":true,"friend":[{"name":"Bob","age":24}],"school":[{"name":"Crown Public School"}]}]}




    This section is empty.


    View Source
    var (
    	// ErrFinished is returned when an operation is performed on
    	// already committed or discarded transaction
    	ErrFinished = errors.New("Transaction has already been committed or discarded")
    	// ErrReadOnly is returned when a write/update is performed on a readonly transaction
    	ErrReadOnly = errors.New("Readonly transaction cannot run mutations or be committed")


    func DeleteEdges

    func DeleteEdges(mu *api.Mutation, uid string, predicates ...string)

      DeleteEdges sets the edges corresponding to predicates on the node with the given uid for deletion. This helper function doesn't run the mutation on the server. Txn needs to be committed in order to execute the mutation.

      {"me":[{"name":"Alice","age":26,"married":true,"schools":[{"name@en":"Crown Public School"}]}]}


      type Dgraph

      type Dgraph struct {
      	// contains filtered or unexported fields

        Dgraph is a transaction aware client to a set of Dgraph server instances.

        func NewDgraphClient

        func NewDgraphClient(clients ...api.DgraphClient) *Dgraph

          NewDgraphClient creates a new Dgraph (client) for interacting with Alphas. The client is backed by multiple connections to the same or different servers in a cluster.

          A single Dgraph (client) is thread safe for sharing with multiple goroutines.

          func (*Dgraph) Alter

          func (d *Dgraph) Alter(ctx context.Context, op *api.Operation) error

            Alter can be used to do the following by setting various fields of api.Operation:

            1. Modify the schema.
            2. Drop a predicate.
            3. Drop the database.
            Example (DropAll)

            func (*Dgraph) Login

            func (d *Dgraph) Login(ctx context.Context, userid string, password string) error

              Login logs in the current client using the provided credentials. Valid for the duration the client is alive.

              func (*Dgraph) NewReadOnlyTxn

              func (d *Dgraph) NewReadOnlyTxn() *Txn

                NewReadOnlyTxn sets the txn to readonly transaction.

                func (*Dgraph) NewTxn

                func (d *Dgraph) NewTxn() *Txn

                  NewTxn creates a new transaction.

                  type Txn

                  type Txn struct {
                  	// contains filtered or unexported fields

                    Txn is a single atomic transaction. A transaction lifecycle is as follows:

                    1. Created using NewTxn.
                    2. Various Query and Mutate calls made.
                    3. Commit or Discard used. If any mutations have been made, It's important
                       that at least one of these methods is called to clean up resources. Discard
                       is a no-op if Commit has already been called, so it's safe to defer a call
                       to Discard immediately after NewTxn.

                    func (*Txn) BestEffort

                    func (txn *Txn) BestEffort() *Txn

                      BestEffort enables best effort in read-only queries. This will ask the Dgraph Alpha to try to get timestamps from memory in a best effort to reduce the number of outbound requests to Zero. This may yield improved latencies in read-bound datasets.

                      This method will panic if the transaction is not read-only. Returns the transaction itself.

                      func (*Txn) Commit

                      func (txn *Txn) Commit(ctx context.Context) error

                        Commit commits any mutations that have been made in the transaction. Once Commit has been called, the lifespan of the transaction is complete.

                        Errors could be returned for various reasons. Notably, ErrAborted could be returned if transactions that modify the same data are being run concurrently. It's up to the user to decide if they wish to retry. In this case, the user should create a new transaction.

                        func (*Txn) Discard

                        func (txn *Txn) Discard(ctx context.Context) error

                          Discard cleans up the resources associated with an uncommitted transaction that contains mutations. It is a no-op on transactions that have already been committed or don't contain mutations. Therefore, it is safe (and recommended) to call as a deferred function immediately after a new transaction is created.

                          In some cases, the transaction can't be discarded, e.g. the grpc connection is unavailable. In these cases, the server will eventually do the transaction clean up itself without any intervention from the client.


                          func (*Txn) Mutate

                          func (txn *Txn) Mutate(ctx context.Context, mu *api.Mutation) (*api.Assigned, error)

                            Mutate allows data stored on Dgraph instances to be modified. The fields in api.Mutation come in pairs, set and delete. Mutations can either be encoded as JSON or as RDFs.

                            If CommitNow is set, then this call will result in the transaction being committed. In this case, an explicit call to Commit doesn't need to be made subsequently.

                            If the mutation fails, then the transaction is discarded and all future operations on it will fail.

                            {"me":[{"name":"Alice","age":26,"loc":{"type":"Point","coordinates":[1.1,2]},"raw_bytes":"cmF3X2J5dGVz","married":true,"friend":[{"name":"Bob","age":24}],"school":[{"name":"Crown Public School"}]}]}
                            Example (Bytes)
                            Me: [{Uid: Name:Alice-new Bytes:[114 97 119 95 98 121 116 101 115]}]
                            Example (DeleteNode)
                            Resp after deleting node: {"me":[],"me2":[{"name":"Bob","age":24}],"me3":[{"name":"Charlie","age":29}]}
                            Example (DeletePredicate)
                            Response after deletion: {Me:[{Uid: Name:Alice Age:26 Married:false Friends:[]}]}
                            Example (Facets)
                            Me: [{Uid: Name:Alice NameOrigin:Indonesia Friends:[{Uid: Name:Bob NameOrigin: Friends:[] Since:2009-11-10 23:00:00 +0000 UTC Family:yes Age:13 Close:true School:[]}] Since:0001-01-01 00:00:00 +0000 UTC Family: Age:0 Close:false School:[{Name:Wellington School Since:2009-11-10 23:00:00 +0000 UTC}]}]
                            Example (List)
                            Example (Upsert)
                            Example (UpsertJSON)

                            func (*Txn) Query

                            func (txn *Txn) Query(ctx context.Context, q string) (*api.Response, error)

                              Query sends a query to one of the connected Dgraph instances. If no mutations need to be made in the same transaction, it's convenient to chain the method, e.g. NewTxn().Query(ctx, "...").

                              Example (Besteffort)
                              Example (Unmarshal)
                              {"me":[{"name":"Alice","age":26,"raw_bytes":"cmF3X2J5dGVz","married":true,"friend":[{"name":"Bob","age":24}],"school":[{"name":"Crown Public School"}]}]}
                              Example (Variables)

                              func (*Txn) QueryWithVars

                              func (txn *Txn) QueryWithVars(ctx context.Context, q string, vars map[string]string) (
                              	*api.Response, error)

                                QueryWithVars is like Query, but allows a variable map to be used. This can provide safety against injection attacks.

                                func (*Txn) Sequencing

                                func (txn *Txn) Sequencing(sequencing api.LinRead_Sequencing)

                                  Sequencing is no longer used


                                  Path Synopsis
                                  Package y contains the code shared by the Go client and Dgraph server.
                                  Package y contains the code shared by the Go client and Dgraph server.