Go
We’re overhauling Dgraph’s docs to make them clearer and more approachable. If you notice any issues during this transition or have suggestions, please let us know.
The Go client communicates with the server on the gRPC port (default value 9080).
The client can be obtained in the usual way via go get
:
The full GoDoc contains documentation for the client API along with examples showing how to use it.
Supported versions
Depending on the version of Dgraph that you are connecting to, you should use a compatible 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” |
v25 APIs
These are experimental APIs that we’re still making changes to. If you have any feedback, please let us know either on Discord or GitHub.
Connection strings
The dgo package supports connecting to a Dgraph cluster using connection
strings. Dgraph connection 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 arguments:
Arg | Value | Description |
---|---|---|
apikey | <key> | a Dgraph Cloud API Key |
bearertoken | <token> | 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:supersecret@dg.example.com: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=<your-api-connection-key> | Connect to a Dgraph Cloud cluster |
dgraph://foo-bar.grpc.hypermode.com?sslmode=verify-ca&bearertoken=<some access token> | Connect to a Dgraph cluster protected by a secure gateway |
Using the Open
function with a connection string:
Advanced client creation
For more control, you can create a client using the NewClient
function.
You can connect to multiple alphas using NewRoundRobinClient
.
Connecting to Dgraph cloud
You can use either Open
or NewClient
to connect to Dgraph Cloud. Note
DialCloud
is marked deprecated and will be removed in later versions.
Using Open
with a connection string:
Using NewClient
:
Dropping all data
In order to drop all data in the Dgraph cluster and start fresh, use the
DropAllNamespaces
function.
Set schema
To set the schema, use the SetSchema
function.
Running a mutation
To run a mutation, use the RunDQL
function.
Running a query
To run a query, use the same RunDQL
function.
Running a query with variables
To run a query with variables, using RunDQLWithVars
.
Running a best effort query
To run a BestEffort
query, use the same RunDQL
function with TxnOption
.
Running a read-only query
To run a ReadOnly
query, use the same RunDQL
function with TxnOption
.
Running a query with rdf response
To get the query response in RDF format instead of JSON format, use the
following TxnOption
.
Running an Upsert
The RunDQL
function also allows you to run upserts as well.
Running a conditional upsert
Creating a new namespace
Dgraph v25 supports namespaces that have names. You can create one using the dgo client.
You can now pass this name to SetSchema
, RunDQL
or similar functions.
Dropping a Namespace
To drop a namespace:
Rename a Namespace
A namespace can be renamed as follows.
List all namespaces
v1 APIs
Create the client
To create a client, dial a connection to Dgraph’s external gRPC port (typically
9080
). The following code snippet shows just one connection. You can connect
to multiple Dgraph Alphas to distribute the workload evenly.
The client can be configured to use gRPC compression:
Multi-tenancy
In multi-tenancy environments, Dgraph
provides a new method LoginIntoNamespace()
, which allows the users to login to
a specific namespace.
In order to create a dgo client, and make the client login into namespace 123
:
In this example, the client logs into namespace 123
using username groot
and
password password
. Once logged in, the client can perform all the operations
allowed to the groot
user of namespace 123
.
Alter the database
To set the schema, set it on a api.Operation
object, and pass it down to the
Alter
method.
api.Operation
contains other fields as well, including drop predicate and drop
all. Drop all is useful if you wish to discard all the data, and start from a
clean slate, without bringing the instance down.
api.Operation
also supports a drop data operation. This operation drops all
the data but preserves the schema. This is useful when the schema is large and
needs to be reused, such as in between unit tests.
Create a transaction
Dgraph supports running distributed ACID transactions. To create a transaction,
just call c.NewTxn()
. This operation doesn’t incur in network calls.
Typically, you’d also want to call a defer txn.Discard(ctx)
to let it
automatically rollback in case of errors. Calling Discard
after Commit
would
be a no-op.
Read-only transactions
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 can’t contain mutations and
trying to call txn.Commit()
results in an error. Calling txn.Discard()
is a
no-op.
Read-only queries can optionally be set as best-effort. Using this flag requests the Dgraph Alpha to try to get timestamps from memory on a best-effort basis to reduce the number of outbound requests to Zero. This may yield improved latencies in read-bound workloads where linearizable reads are not strictly needed.
Run a query
You can run a query by calling txn.Query
. The response would contain a JSON
field, which has the JSON encoded result. You can unmarshal it into Go struct
via json.Unmarshal
.
Query with RDF response
You can get query result as a RDF response by calling txn.QueryRDF
. The
response would contain a Rdf
field, which has the RDF encoded result.
If you are querying only for uid
values, use a JSON format response.
Run a mutation
txn.Mutate
would run the mutation. It takes in a api.Mutation
object, which
provides two main ways to set data: JSON and RDF N-Quad. You can choose
whichever way is convenient.
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 planning on using RDF.
We’re going to continue using JSON. You could modify the Go structs parsed from the query, and marshal them back into JSON.
Sometimes, you only want to commit mutation, without querying anything further.
In such cases, you can use a CommitNow
field in api.Mutation
to indicate
that the mutation must be immediately committed.
Commit the transaction
Once all the queries and mutations are done, you can commit the transaction. It returns an error in case the transaction couldn’t be committed.
Complete example
This is an example from the GoDoc.
It shows how to create a Node
with name Alice
, while also creating her
relationships with other nodes.
loc
predicate is of type geo
and can be easily marshaled and unmarshaled
into a Go struct. More such examples are present as part of the GoDoc.
You can also download this complete example file from our GitHub repository.
Example output result: