Skip to content

Instantly share code, notes, and snippets.

@insanitybit
Created June 5, 2018 03:19
Show Gist options
  • Save insanitybit/2838b2b604def4d41c59ea344d56bc35 to your computer and use it in GitHub Desktop.
Save insanitybit/2838b2b604def4d41c59ea344d56bc35 to your computer and use it in GitHub Desktop.
package main
import (
"context"
"encoding/json"
"log"
"github.com/dgraph-io/dgo"
"github.com/dgraph-io/dgo/protos/api"
"google.golang.org/grpc"
)
type Process struct {
ImagePath string `json:"image_path, omitempty"`
ExecName string `json:"exe_name, omitempty"`
Pid int `json:"pid, omitempty"`
CreateTime int `json:"create_time, omitempty"`
Children []Process `json:"children, omitempty"`
}
func main() {
ctx := context.Background()
// Getting connection
d, err := grpc.Dial("localhost:9080", grpc.WithInsecure())
if err != nil {
log.Fatal(err)
}
c := dgo.NewDgraphClient(
api.NewDgraphClient(d),
)
// Setting the schema
c.Alter(context.Background(), &api.Operation{
Schema: `
image_path: string @index(hash).
exe_name: string @index(hash).
pid: int @index(int).
create_time: int .
children: uid .
`,
})
p := Process{
ImagePath: "/home/word.exe",
ExecName: "word.exe",
Pid: 101,
CreateTime: 100001,
}
pAsJson, err := json.Marshal(&p)
if err != nil {
log.Fatalln("Error marshalling process: ", err)
}
// Create transaction for adding record
txn := c.NewTxn()
defer txn.Discard(ctx)
_, err = txn.Mutate(context.Background(), &api.Mutation{SetJson: pAsJson})
if err != nil {
log.Fatalln("Error creating mutation: ", err)
}
err = txn.Commit(ctx)
if err != nil {
log.Fatalln("Error commiting transaction: ", err)
}
// Create transaction for querying
queryTxn := c.NewTxn()
defer queryTxn.Discard(ctx)
const q = `
{
question(func: eq(exe_name, "word.exe"))
{
pid
}
}
`
resp, err := queryTxn.Query(ctx, q)
if err != nil {
log.Fatalln("Error querying dgraph: ",err)
}
log.Println(string(resp.GetJson()))
// Results in: {"question":[{"pid":101}]}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment