Hey
I was trying to Unmarshal a geo property into a struct in golang, but I haven’t found any examples on how to do that. How do I go about doing that?
Hey
I was trying to Unmarshal a geo property into a struct in golang, but I haven’t found any examples on how to do that. How do I go about doing that?
Hey @felipellrocha
This is how you do it in v0.8.3
.
conn, err := grpc.Dial("127.0.0.1:9080", grpc.WithInsecure())
x.Checkf(err, "While trying to dial gRPC")
defer conn.Close()
clientDir, err := ioutil.TempDir("", "client_")
x.Check(err)
defer os.RemoveAll(clientDir)
dgraphClient := client.NewDgraphClient(
[]*grpc.ClientConn{conn}, client.DefaultOptions, clientDir)
req := client.Req{}
alice, err := dgraphClient.NodeBlank("alice")
if err != nil {
log.Fatal(err)
}
e := alice.Edge("name")
e.SetValueString("Alice")
err = req.Set(e)
x.Check(err)
e = alice.Edge("loc")
err = e.SetValueGeoJson(`{"Type":"Point", "Coordinates":[1.1,2.0]}`)
x.Check(err)
err = req.Set(e)
x.Check(err)
e = alice.Edge("city")
err = e.SetValueGeoJson(`{
"Type":"Polygon",
"Coordinates":[[[0.0,0.0], [2.0,0.0], [2.0, 2.0], [0.0, 2.0], [0.0, 0.0]]]
}`)
x.Check(err)
err = req.Set(e)
x.Check(err)
req.SetQuery(`mutation {
schema {
name: string @index(exact) .
}
}
{
q(func: eq(name, "Alice")) {
name
loc
city
}
}`)
resp, err := dgraphClient.Run(context.Background(), &req)
if err != nil {
log.Fatalf("Error in getting response from server, %s", err)
}
type Alice struct {
Name string `json:"name"`
Loc []byte `json:"loc"`
City []byte `json:"city"`
}
type Res struct {
Root Alice `json:"q"`
}
var r Res
err = client.Unmarshal(resp.N, &r)
x.Check(err)
fmt.Printf("Alice: %+v\n\n", r.Root)
loc, err := wkb.Unmarshal(r.Root.Loc)
x.Check(err)
city, err := wkb.Unmarshal(r.Root.City)
x.Check(err)
fmt.Printf("Loc: %+v\n\n", loc)
fmt.Printf("City: %+v\n\n", city)
err = dgraphClient.Close()
x.Check(err)
The geo fields are unmarshalled into a byte slice, which is later unmarshalled using wkb.Unmarshal
.
This is how you would do it from the next version (which should be out in a week) https://godoc.org/github.com/dgraph-io/dgraph/client#example-package--SetObject. See the Location
field.
We should also add this in the Clients page in our documentation.
This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.