Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
D

dgo

> 编程语言
Open source

Official Dgraph Go client

389 stars0 likes1 views
WebsiteGitHub

About

Official Dgraph Go client

dgo

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

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

Use Github Issues for reporting issues about this repository.

Table of contents

  • Supported Versions
  • New APIs in v25
    • Connection Strings
    • Advanced Client Creation
    • Dropping All Data
    • Set Schema
    • Running a Mutation
    • Running a Query
    • Running a Query With Variables
    • Running a Best Effort Query
    • Running a ReadOnly Query
    • Running a Query with RDF Response
    • Running an Upsert
    • Running a Conditional Upsert
    • Creating a New Namespace
    • Dropping a Namespace
    • List All Namespaces
  • Existing APIs
    • Creating a Client
    • Login into a namespace
    • Altering the database
    • Creating a transaction
    • Running a mutation
    • Running a query
    • Query with RDF response
    • Running an Upsert: Query + Mutation
    • Running Conditional Upsert
    • Committing a transaction
    • Setting Metadata Headers
  • Development
    • Running tests

Supported Versions

Depending on the version of Dgraph that you are connecting to, you will have to use a different version of this client and their corresponding import paths.

Dgraph version dgo version dgo import path
dgraph 23.X.Y dgo 230.X.Y "github.com/dgraph-io/dgo/v230"
dgraph 24.X.Y dgo 240.X.Y "github.com/dgraph-io/dgo/v240"
dgraph 25.X.Y dgo 240.X.Y "github.com/dgraph-io/dgo/v240"
dgraph 25.X.Y dgo 250.X.Y "github.com/dgraph-io/dgo/v250"

New APIs in v25

Connection Strings

The dgo package supports connecting to a Dgraph cluster using connection strings. Dgraph connections strings take the form dgraph://{username:password@}host:port?args.

username and password are optional. If username is provided, a password must also be present. If supplied, these credentials are used to log into a Dgraph cluster through the ACL mechanism.

Valid connection string args:

Arg Value Description
apikey \ a Dgraph Cloud API Key
bearertoken \ an access token
sslmode disable | require | verify-ca TLS option, the default is disable. If verify-ca is set, the TLS certificate configured in the Dgraph cluster must be from a valid certificate authority.

Some example connection strings:

Value Explanation
dgraph://localhost:9080 Connect to localhost, no ACL, no TLS
dgraph://sally:[email protected]:443?sslmode=verify-ca Connect to remote server, use ACL and require TLS and a valid certificate from a CA
dgraph://foo-bar.grpc.us-west-2.aws.cloud.dgraph.io:443?sslmode=verify-ca&apikey=\ Connect to a Dgraph Cloud cluster
dgraph://foo-bar.grpc.example.com?sslmode=verify-ca&bearertoken=\ Connect to a Dgraph cluster protected by a secure gateway

Using the Open function with a connection string:

go
// open a connection to an ACL-enabled, non-TLS cluster and login as groot
client, err := dgo.Open("dgraph://groot:password@localhost:8090")
// Check error
defer client.Close()
// Use the clients

Advanced Client Creation

For more control, you can create a client using the NewClient function.

go
client, err := dgo.NewClient("localhost:9181",
  // add Dgraph ACL credentials
  dgo.WithACLCreds("groot", "password"),
  // add insecure transport credentials
  dgo.WithGrpcOption(grpc.WithTransportCredentials(insecure.NewCredentials())),
)
// Check error
defer client.Close()
// Use the client

You can connect to multiple alphas using NewRoundRobinClient.

go
client, err := dgo.NewRoundRobinClient([]string{"localhost:9181", "localhost:9182", "localhost:9183"},
  // add Dgraph ACL credentials
  dgo.WithACLCreds("groot", "password"),
  // add insecure transport credentials
  dgo.WithGrpcOption(grpc.WithTransportCredentials(insecure.NewCredentials())),
)
// Check error
defer client.Close()
// Use the client

Dropping All Data

In order to drop all data in the Dgraph Cluster and start fresh, use the DropAll function.

go
err := client.DropAll(context.TODO())
// Handle error

Set Schema

To set the schema, use the SetSchema function.

go
sch := `
  name: string @index(exact) .
  email: string @index(exact) @unique .
  age: int .
`
err := client.SetSchema(context.TODO(), sch)
// Handle error

Running a Mutation

To run a mutation, use the RunDQL function.

go
mutationDQL := `{
  set {
    _:alice  "Alice" .
    _:alice  "[email protected]" .
    _:alice  "29" .
  }
}`
resp, err := client.RunDQL(context.TODO(), mutationDQL)
// Handle error
// Print map of blank UIDs
fmt.Printf("%+v\n", resp.Uids)

Running a Query

To run a query, use the same RunDQL function.

go
queryDQL := `{
  alice(func: eq(name, "Alice")) {
    name
    email
    age
  }
}`
resp, err := client.RunDQL(context.TODO(), queryDQL)
// Handle error
fmt.Printf("%s\n", resp.Json)

Running a Query With Variables

To run a query with variables, using RunDQLWithVars.

go
queryDQL = `query Alice($name: string) {
  alice(func: eq(name, $name)) {
    name
    email
    age
  }
}`
vars := map[string]string{"$name": "Alice"}
resp, err := client.RunDQLWithVars(context.TODO(), queryDQL, vars)
// Handle error
fmt.Printf("%s\n", resp.Json)

Running a Best Effort Query

To run a BestEffort query, use the same RunDQL function with TxnOption.

go
queryDQL := `{
  alice(func: eq(name, "Alice")) {
    name
    email
    age
  }
}`
resp, err := client.RunDQL(context.TODO(), queryDQL, dgo.WithBestEffort())
// Handle error
fmt.Printf("%s\n", resp.Json)

Running a ReadOnly Query

To run a ReadOnly query, use the same RunDQL function with TxnOption.

go
queryDQL := `{
  alice(func: eq(name, "Alice")) {
    name
    email
    age
  }
}`
resp, err := client.RunDQL(context.TODO(), queryDQL, dgo.WithReadOnly())
// Handle error
fmt.Printf("%s\n", resp.Json)

Running a Query with RDF Response

To get the query response in RDF format instead of JSON format, use the following TxnOption.

go
queryDQL := `{
  alice(func: eq(name, "Alice")) {
    name
    email
    age
  }
}`
resp, err = client.RunDQL(context.TODO(), queryDQL, dgo.WithResponseFormat(api_v2.RespFormat_RDF))
// Handle error
fmt.Printf("%s\n", resp.Rdf)

Running an Upsert

The RunDQL function also allows you to run upserts as well.

go
upsertQuery := `upsert {
  query {
    user as var(func: eq(email, "[email protected]"))
  }
  mutation {
    set {
      uid(user)  "30" .
      uid(user)  "Alice Sayum" .
    }
  }
}`
resp, err := client.RunDQL(context.TODO(), upsertQuery)
// Handle error
fmt.Printf("%s\n", resp.Json)
fmt.Printf("%+v\n", resp.Uids)

Running a Conditional Upsert

go
upsertQuery := `upsert {
  query {
    user as var(func: eq(email, "[email protected]"))
  }
  mutation @if(eq(len(user), 1)) {
    set {
      uid(user)  "30" .
      uid(user)  "Alice Sayum" .
    }
  }
}`
resp, err := client.RunDQL(context.TODO(), upsertQuery)
// Handle error
fmt.Printf("%s\n", resp.Json)

Creating a New Namespace

Dgraph v25 supports creating namespaces using grpc API. You can create one using the dgo client.

go
_, err := client.CreateNamespace(context.TODO())
// Handle error

Dropping a Namespace

To drop a namespace:

go
err := client.DropNamespace(context.TODO())
// Handle error

List All Namespaces

go
namespaces, err := client.ListNamespaces(context.TODO())
// Handle error
fmt.Printf("%+v\n", namespaces)

Existing APIs

Creating a Client

dgraphClient object can be initialized 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.

go
conn, err := grpc.Dial("localhost:9080", grpc.WithInsecure())
// Check error
defer conn.Close()
dgraphClient := dgo.NewDgraphClient(api.NewDgraphClient(conn))

Login into a namespace

If your server has Access Control Lists enabled (Dgraph v1.1 or above), the client must be logged in for accessing data. If you do not use the WithACLCreds option with NewClient or a connection string with username:password, use the Login endpoint.

Calling login will obtain and remember the access and refresh JWT tokens. All subsequent operations via the logged in client will send along the stored access token.

go
err := dgraphClient.Login(ctx, "user", "passwd")
// Check error

If your server additionally has namespaces (Dgraph v21.03 or above), use the LoginIntoNamespace API.

go
err := dgraphClient.LoginIntoNamespace(ctx, "user", "passwd", 0x10)
// Check error

Altering the database

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

go
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.

Starting Dgraph version 20.03.0, indexes can be computed in the background. You can set RunInBackground field of the api.Operation to true before passing it to the Alter function. You can find m

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Go

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言