I finally did it.
I can refer to dgo/example_set_object_test.go at master · dgraph-io/dgo · GitHub.
There every one who wonder can see how to link nodes.
There is my working prototype. Is that Go way to do this?
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"github.com/dgraph-io/dgo/v210"
"github.com/dgraph-io/dgo/v210/protos/api"
"google.golang.org/grpc"
)
const schema = `rule.name: string @index(exact) .
device.name: string @index(exact) .
device.rules: [uid] .
`
type Rule struct {
Uid int `json:"uid,omitempty"`
Name string `json:"rule.name,omitempty"`
}
type Device struct {
Uid int `json:"uid,omitempty"`
Name string `json:"device.name,omitempty"`
Rules []Rule `json:"device.rules,omitempty"`
}
var ctx = context.TODO()
func main() {
// Set db connection
conn, err := grpc.Dial("localhost:9080", grpc.WithInsecure())
if err != nil {
log.Fatal(err)
}
defer conn.Close()
dgraphClient := dgo.NewDgraphClient(api.NewDgraphClient(conn))
op := &api.Operation{
Schema: schema,
}
err = dgraphClient.Alter(ctx, op)
if err != nil {
panic(err)
}
// Create rule
txn := dgraphClient.NewTxn()
defer txn.Discard(ctx)
r := Rule{
Uid: 1,
Name: "Rule1",
}
pb, err := json.Marshal(r)
if err != nil {
log.Fatal(err)
}
mu := &api.Mutation{
SetJson: pb,
CommitNow: true,
}
res, err := txn.Mutate(ctx, mu)
if err != nil {
log.Fatal(err)
}
fmt.Println(res)
// Create Device
txn = dgraphClient.NewTxn()
defer txn.Discard(ctx)
d := Device{
Uid: 2,
Name: "Device1",
Rules: []Rule{{Uid: 1}},
}
pb, err = json.Marshal(d)
if err != nil {
log.Fatal(err)
}
mu = &api.Mutation{
SetJson: pb,
CommitNow: true,
}
res, err = txn.Mutate(ctx, mu)
if err != nil {
log.Fatal(err)
}
fmt.Println(res)
}
As I understood it will not fully copy rule in the device but just write it uid in device.rules.