my golang client
exp:
first instert base data
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"github.com/dgraph-io/dgraph/client"
"github.com/dgraph-io/dgraph/protos/api"
"google.golang.org/grpc"
)
type A struct {
Uid string `json:"uid,omitempty"`
Name string `json:"testname,omitempty"`
}
type B struct {
Uid string `json:"uid,omitempty"`
Name string `json:"testname,omitempty"`
In []A `json:"In,omitempty"`
}
func main() {
var a A
var aa A
var b B
a.Name = "test-1a"
aa.Name = "test-1aa"
b.Name = "test-1b"
b.In = append(b.In, a)
conn, err := grpc.Dial("127.0.0.1:9080", grpc.WithInsecure())
if err != nil {
log.Fatal("While trying to dial gRPC")
}
defer conn.Close()
dc := api.NewDgraphClient(conn)
dg := client.NewDgraphClient(dc)
op := &api.Operation{}
op.Schema = `
testname: string @index(exact) .
In: uid @reverse .
`
ctx := context.Background()
err = dg.Alter(ctx, op)
if err != nil {
log.Fatal(err)
}
mu := &api.Mutation{
CommitNow: true,
}
pb, err := json.Marshal(b)
if err != nil {
log.Fatal(err)
}
mu.SetJson = pb
_, err = dg.NewTxn().Mutate(ctx, mu)
if err != nil {
log.Fatal(err)
}
variables := map[string]string{"$testname": "test-1b"}
q := `query Me($testname: string){
me(func: eq(testname,$testname)) {
uid
}
}`
resp, err := dg.NewTxn().QueryWithVars(ctx, q, variables)
if err != nil {
log.Fatal(err)
}
type Root struct {
Me []B `json:"me"`
}
var r Root
err = json.Unmarshal(resp.Json, &r)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(resp.Json))
}
result:
insert New data connect to base data test-1b
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"github.com/dgraph-io/dgraph/client"
"github.com/dgraph-io/dgraph/protos/api"
"google.golang.org/grpc"
)
type A struct {
Uid string `json:"uid,omitempty"`
Name string `json:"testname,omitempty"`
}
type B struct {
Uid string `json:"uid,omitempty"`
Name string `json:"testname,omitempty"`
In []A `json:"In,omitempty"`
}
func main() {
var aa A
var b B
aa.Name = "test-1aa"
b.Name = "test-1b"
b.Uid = "0x2738"
b.In = append(b.In, aa)
conn, err := grpc.Dial("127.0.0.1:9080", grpc.WithInsecure())
if err != nil {
log.Fatal("While trying to dial gRPC")
}
defer conn.Close()
dc := api.NewDgraphClient(conn)
dg := client.NewDgraphClient(dc)
ctx := context.Background()
mu := &api.Mutation{
CommitNow: true,
}
pb, err := json.Marshal(b)
if err != nil {
log.Fatal(err)
}
mu.SetJson = pb
_, err = dg.NewTxn().Mutate(ctx, mu)
if err != nil {
log.Fatal(err)
}
variables := map[string]string{"$testname": "test-1b"}
q := `query Me($testname: string){
me(func: eq(testname,$testname)) {
expand(_all_){
expand(_all_)}
}
}`
resp, err := dg.NewTxn().QueryWithVars(ctx, q, variables)
if err != nil {
log.Fatal(err)
}
type Root struct {
Me []B `json:"me"`
}
var r Root
err = json.Unmarshal(resp.Json, &r)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(resp.Json))
}
result:
The new data “”test-1aa“” already in the base data test-1b,
Just modifying and updates by struct’s Uid