diff --git a/client/client.go b/client/client.go index 9792f71dae7a42a8de4614200453ccd1c9006445..f7a037da5a644f65daf54b75c44baecfe6ddaadb 100644 --- a/client/client.go +++ b/client/client.go @@ -455,7 +455,7 @@ func (e *Edge) SetValueBytes(val []byte) error { return nil } -// AddFacet adds the key, value pair as facets on Edge e. No checking is done. +// AddFacet adds the key, value pair as facets on Edge e. No checking is done. func (e *Edge) AddFacet(key, val string) { e.nq.Facets = append(e.nq.Facets, &protos.Facet{ Key: key, diff --git a/wiki/content/clients/index.md b/wiki/content/clients/index.md index f61f07c4bd0919ea2aedcae372461778c025e4b5..a1ddfce357e448c3ee8d2eb321aa312d152618fb 100644 --- a/wiki/content/clients/index.md +++ b/wiki/content/clients/index.md @@ -5,9 +5,10 @@ title = "Clients" ## Implementation -Clients communicate with the server using [Protocol Buffers](https://developers.google.com/protocol-buffers) over [gRPC](http://www.grpc.io/). This requires [defining services](http://www.grpc.io/docs/#defining-a-service) and data types in a ''proto'' file and then generating client and server side code using the [protoc compiler](https://github.com/google/protobuf). +All clients can communicate with the server via the HTTP endpoint (set with option `--port` when starting Dgraph). Queries and mutations can be submitted and JSON is returned. + +Go clients can use the clients package and communicate with the server over [gRPC](http://www.grpc.io/). Internally this uses [Protocol Buffers](https://developers.google.com/protocol-buffers) and the proto file used by Dgraph is located at [graphresponse.proto](https://github.com/dgraph-io/dgraph/blob/master/protos/graphresponse.proto). -The proto file used by Dgraph is located at [graphresponse.proto](https://github.com/dgraph-io/dgraph/blob/master/protos/graphp/graphresponse.proto). ## Languages @@ -15,306 +16,25 @@ The proto file used by Dgraph is located at [graphresponse.proto](https://github [](https://godoc.org/github.com/dgraph-io/dgraph/client) -After you have the followed [Get started]({{< relref "get-started/index.md">}}) and got the server running on `127.0.0.1:8080` and (for gRPC) `127.0.0.1:9080`, you can use the Go client to run queries and mutations as shown in the example below. - -{{% notice "note" %}}The example below would store values with the correct types only if the -correct [schema type]({{< relref "query-language/index.md#schema" >}}) is specified in the mutation, otherwise everything would be converted to schema type and stored. Schema is derived based on first mutation received by the server. If first mutation is of default type then everything would be stored as default type.{{% /notice %}} +The go client communicates with the server on the grpc port (set with option `--grpc_port` when starting Dgraph). #### Installation -To get the Go client, you can run +Go get the client: ``` -go get -u -v github.com/dgraph-io/dgraph/client github.com/dgraph-io/dgraph/protos +go get -u -v github.com/dgraph-io/dgraph/client ``` -#### Example - -The working example below shows the common operations that one would perform on a graph. +#### Examples -``` -package main - -import ( - "context" - "flag" - "fmt" - "time" - - "github.com/dgraph-io/dgraph/client" - "github.com/dgraph-io/dgraph/x" - "google.golang.org/grpc" -) - -var ( - dgraph = flag.String("d", "127.0.0.1:9080", "Dgraph server address") -) - -type nameFacets struct { - Since time.Time `dgraph:"since"` - Alias string `dgraph:"alias"` -} +The client [GoDoc](https://godoc.org/github.com/dgraph-io/dgraph/client) has specifications of all functions and examples. -type friendFacets struct { - Close bool `dgraph:"close"` -} +Larger examples can be found [here](https://github.com/dgraph-io/dgraph/tree/master/wiki/resources/examples/goclient). And [this](https://open.dgraph.io/post/client0.8.0) blog post explores the examples further. -type Person struct { - Name string `dgraph:"name"` - NameFacets nameFacets `dgraph:"name@facets"` - Birthday time.Time `dgraph:"birthday"` - Location []byte `dgraph:"loc"` - Salary float64 `dgraph:"salary"` - Age int `dgraph:"age"` - Married bool `dgraph:"married"` - ByteDob []byte `dgraph:"bytedob"` - Friends []Person `dgraph:"friend"` - FriendFacets []friendFacets `dgraph:"@facets"` -} +The app [dgraphloader](https://github.com/dgraph-io/dgraph/tree/master/cmd/dgraphloader) uses the client interface to batch concurrent mutations. -type Res struct { - Root Person `dgraph:"me"` -} - -func main() { - conn, err := grpc.Dial(*dgraph, grpc.WithInsecure()) - x.Checkf(err, "While trying to dial gRPC") - defer conn.Close() - - dgraphClient := client.NewDgraphClient([]*grpc.ClientConn{conn}, client.DefaultOptions) - - req := client.Req{} - person1, err := dgraphClient.NodeBlank("person1") - x.Check(err) - - // Creating a person node, and adding a name attribute to it. - e := person1.Edge("name") - err = e.SetValueString("Steven Spielberg") - x.Check(err) - e.AddFacet("since", "2006-01-02T15:04:05") - e.AddFacet("alias", `"Steve"`) - req.Set(e) - - e = person1.Edge("birthday") - err = e.SetValueDatetime(time.Date(1991, 2, 1, 0, 0, 0, 0, time.UTC)) - x.Check(err) - req.Set(e) - - e = person1.Edge("loc") - err = e.SetValueGeoJson(`{"type":"Point","coordinates":[-122.2207184,37.72129059]}`) - x.Check(err) - req.Set(e) - - e = person1.Edge("salary") - err = e.SetValueFloat(13333.6161) - x.Check(err) - req.Set(e) - - e = person1.Edge("age") - err = e.SetValueInt(25) - x.Check(err) - req.Set(e) - - e = person1.Edge("married") - err = e.SetValueBool(true) - x.Check(err) - req.Set(e) - - e = person1.Edge("bytedob") - err = e.SetValueBytes([]byte("01-02-1991")) - x.Check(err) - req.Set(e) - - person2, err := dgraphClient.NodeBlank("person2") - x.Check(err) - - e = person2.Edge("name") - err = e.SetValueString("William Jones") - x.Check(err) - req.Set(e) - - e = person1.Edge("friend") - err = e.ConnectTo(person2) - x.Check(err) - e.AddFacet("close", "true") - req.Set(e) - - resp, err := dgraphClient.Run(context.Background(), &req) - x.Check(err) - - req = client.Req{} - req.SetQuery(fmt.Sprintf(`{ - me(func: uid(%v)) { - _uid_ - name @facets - now - birthday - loc - salary - age - married - bytedob - friend @facets { - _uid_ - name - } - } - }`, person1)) - resp, err = dgraphClient.Run(context.Background(), &req) - x.Check(err) - - var r Res - err = client.Unmarshal(resp.N, &r) - fmt.Printf("Steven: %+v\n\n", r.Root) - fmt.Printf("William: %+v\n", r.Root.Friends[0]) - - req = client.Req{} - // Here is an example of deleting an edge - e = person1.Edge("friend") - err = e.ConnectTo(person2) - x.Check(err) - req.Delete(e) - resp, err = dgraphClient.Run(context.Background(), &req) - x.Check(err) - - err = dgraphClient.Close() - x.Check(err) -} -``` - -{{% notice "note" %}}Type for the facets are automatically interpreted from the value. If you want it to -be interpreted as string, it has to be a raw string literal with `""` as shown above for `alias` facet.{{% /notice %}} - -An appropriate schema for the above example would be -``` -curl localhost:8080/query -XPOST -d $' -mutation { - schema { - now: dateTime . - birthday: date . - age: int . - salary: float . - name: string . - loc: geo . - married: bool . - } -}' | python -m json.tool | less -``` - -Apart from the above syntax, you could perform all the queries and mutations listed on [Query Language]({{< relref "query-language/index.md" >}}). For example you could do this. - -``` -req := client.Req{} -req.SetQuery(` -mutation { - set { - <class1> <student> _:x . - <class1> <name> "awesome class" . - _:x <name> "alice" . - _:x <planet> "Mars" . - _:x <friend> _:y . - _:y <name> "bob" . - } -} -{ - class(id:class1) { - name - student { - name - planet - friend { - name - } - } - } -}`) -resp, err := c.Run(context.Background(), req.Request()) -if err != nil { - log.Fatalf("Error in getting response from server, %s", err) -} -fmt.Printf("%+v\n", resp) -``` - -Here is an example of how you could use the Dgraph client to do batch mutations concurrently. -This is what the **dgraphloader** uses internally. -``` -package main - -import ( - "bufio" - "bytes" - "compress/gzip" - "io" - "log" - "os" - - "google.golang.org/grpc" - - "github.com/dgraph-io/dgraph/client" - "github.com/dgraph-io/dgraph/rdf" - "github.com/dgraph-io/dgraph/x" -) - -func ExampleBatchMutation() { - conn, err := grpc.Dial("127.0.0.1:9080", grpc.WithInsecure()) - x.Checkf(err, "While trying to dial gRPC") - defer conn.Close() - - // Start a new batch with batch size 1000 and 100 concurrent requests. - bmOpts := client.BatchMutationOptions{ - Size: 1000, - Pending: 100, - PrintCounters: false, - } - dgraphClient := client.NewDgraphClient(conn, bmOpts) - - // Process your file, convert data to a protos.NQuad and add it to the batch. - // For each edge, do a BatchSet (this would typically be done in a loop - // after processing the data into edges). Here we show example of reading a - // file with RDF data, converting it to edges and adding it to the batch. - - f, err := os.Open("goldendata.rdf.gz") - x.Check(err) - defer f.Close() - gr, err := gzip.NewReader(f) - x.Check(err) - - var buf bytes.Buffer - bufReader := bufio.NewReader(gr) - var line int - for { - err = x.ReadLine(bufReader, &buf) - if err != nil { - break - } - line++ - nq, err := rdf.Parse(buf.String()) - if err == rdf.ErrEmpty { // special case: comment/empty line - buf.Reset() - continue - } else if err != nil { - log.Fatalf("Error while parsing RDF: %v, on line:%v %v", err, line, buf.String()) - } - buf.Reset() - - nq.Subject = Node(nq.Subject, dgraphClient) - if len(nq.ObjectId) > 0 { - nq.ObjectId = Node(nq.ObjectId, dgraphClient) - } - if err = dgraphClient.BatchSet(client.NewEdge(nq)); err != nil { - log.Fatal("While adding mutation to batch: ", err) - } - } - if err != io.EOF { - x.Checkf(err, "Error while reading file") - } - // Wait for all requests to complete. This is very important, else some - // data might not be sent to server. - dgraphClient.BatchFlush() - err = dgraphClient.Close() - x.Check(err) -} -``` +{{% notice "note" %}}As with mutations through a mutation block, [schema type]({{< relref "query-language/index.md#schema" >}}) needs to be set for the edges, or schema is derived based on first mutation received by the server. {{% /notice %}} ### Python {{% notice "incomplete" %}}A lot of development has gone into the Go client and the Python client is not up to date with it. We are looking for help from contributors to bring it up to date.{{% /notice %}} diff --git a/wiki/resources/examples/goclient/README.md b/wiki/resources/examples/goclient/README.md new file mode 100644 index 0000000000000000000000000000000000000000..6fe2ed6cbac598d8f5caaa8903d035ad42e5752d --- /dev/null +++ b/wiki/resources/examples/goclient/README.md @@ -0,0 +1,9 @@ +# go client examples + +Examples of using the go client with Dgraph. Built for Dgraph version 0.8. + +* crawlerRDF queries Dgraph, unmarshals results into custom structs and writes out an RDF file that can be loaded with dgraphloader. +* crawlermutation multithreaded crawler that shows how to use client with go routines. Concurrent crawlers query a source Dgraph, unmarshal into custom structs and write to a target Dgraph. Shows how to issue mutations using requests in client. +* movielensbatch reads from CSV and uses the client batch interface to write to Dgraph. + +Check out the [blog post](https://open.dgraph.io/post/client0.8.0) about these examples. \ No newline at end of file diff --git a/wiki/resources/examples/goclient/crawlerRDF/.gitignore b/wiki/resources/examples/goclient/crawlerRDF/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..e306b518c8b89a80696fb588738936cb2c97b38a --- /dev/null +++ b/wiki/resources/examples/goclient/crawlerRDF/.gitignore @@ -0,0 +1,2 @@ +/crawler +/crawl.rdf.gz diff --git a/wiki/resources/examples/goclient/crawlerRDF/crawler.go b/wiki/resources/examples/goclient/crawlerRDF/crawler.go new file mode 100644 index 0000000000000000000000000000000000000000..56df1b79ca544f6b0026fb067774b786199fbfe2 --- /dev/null +++ b/wiki/resources/examples/goclient/crawlerRDF/crawler.go @@ -0,0 +1,682 @@ +/* + * Copyright 2016 Dgraph Labs, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + +/* + + +*** Check out the blog post about this code : https://open.dgraph.io/post/client0.8.0 *** + + +This program is an example of how to use the Dgraph go client. It is one of two example crawlers. +The other, crawlerMutations, is more focused on running concurrent mutations through the Dgraph +client. This crawler is about querying and unmarshalling results. + +The Dgraph client interface has docs here : https://godoc.org/github.com/dgraph-io/dgraph/client + + + +When we made our tour (https://tour.dgraph.io/) we needed a dataset users could load quickly, +but with enough complexity to demostrate interesting queries. We decided a subset of +our 21million dataset was just right. But we can't just take the first n-lines from the +input file - who knows what connections in the graph we'd get or miss if we did that. It's a graph, +so the best was to make a subset is to crawl it. + +This program crawls a dgraph database loaded with the 21million movie dataset; data available +here : https://github.com/dgraph-io/benchmarks/tree/master/data. At Dgraph we use this dataset +for the examples in our docs. There's instructions on starting up Dgraph and loading this +dataset in our docs here : https://docs.dgraph.io/get-started/. + +Given a loose bound on the number of edges in the output graph (edgeBound), this crawler crawls by +directors, keeping a queue of unvisited directors. For each director it takes off the queue, it +gets all their movies and then queues the directors that actors in those movies have worked for. +The crawler stops after the director whose movies make the crawl exceed the edge count. This way +the output is complete for movies and directors, but won't have every movie for all the actors the +crawler has found. + +When the crawl finishes a gzipped RDF file is written. + + +Run with '--help' to see options. You may want to run with '> crawl.log 2>&1' to redirect logging +output to a file. For example: + +./crawler --edges 500000 > crawl.log 2>&1 + +This crawler outputs gzipped rdf. The output file can be loaded into a Dgraph instance with + +dgraphloader --s <schemafile> --r crawl.rdf.gz + +The schema could be the same as 21million (https://github.com/dgraph-io/benchmarks/blob/master/data/21million.schema), +or + +director.film : uid @reverse @count . +actor.film : uid @count . +genre : uid @reverse @count . +initial_release_date : datetime @index . +name : string @index(term, exact, fulltext, trigram) . + + +*** Check out the blog post about this code : https://open.dgraph.io/post/client0.8.0 *** + +*/ + +package main + +import ( + "context" + "flag" + "fmt" + "io/ioutil" + "log" + "os" + "strings" + "time" + + "compress/gzip" + + "google.golang.org/grpc" + //"google.golang.org/grpc/metadata" // for debug mode + //"github.com/gogo/protobuf/proto" // for with fmt.Printf("Raw Response: %+v\n", proto.MarshalTextString(resp)) + + "github.com/dgraph-io/dgraph/client" + "github.com/dgraph-io/dgraph/protos" + + "github.com/satori/go.uuid" +) + +var ( + dgraph = flag.String("d", "127.0.0.1:9080", "Dgraph gRPC server address") + edgeBound = flag.Int("edges", 50000, "Stop crawling directors after we've made this many edges") + outfile = flag.String("o", "crawl.rdf.gz", "Output file") +) + +// Types namedNode, director, actor, genre, character, movie and performance +// represent the structures in the movie graph. A movie has a name, release +// date, unique id, and a list of genres, directors and performances. A +// performance represents a character being played by an actor in the movie. +// For actors, directors, genres and characters all we are going to crawl is a name. +// The unique ID (the UID in dgraph) is needed throughout, because we need to +// tick off what we have crawled, so we don't visit things twice. +// +// Dgraph will unpack queries into these structures with client.Unmarshal(), we just need to say +// what goes where. +type namedNode struct { // see also query directorByNameTemplate and readDirectors where the query is unmarshalled into this struct + ID uint64 `dgraph:"_uid_"` // Use `dgraph:"edgename"` to tell client.Unmarshal() where to put which edge in your struct. + Name string `dgraph:"name@en"` // Struct fields must be exported (have an intial capital letter) to be accesible to client.Unmarshal(). +} + +type director namedNode +type actor namedNode +type genre namedNode +type character namedNode + +type movie struct { // see also query directorsMoviesTemplate and visitDirector where the query is unmarshalled into this struct + ReleaseDate time.Time `dgraph:"initial_release_date"` // Often just use the edge name and a reasonable type. + ID uint64 `dgraph:"_uid_"` // _uid_ is extracted to uint64 just like any other edge. + Name string `dgraph:"EnglishName"` // If there is an alias on the edge, use the alias. + NameDE string `dgraph:"GermanName"` + NameIT string `dgraph:"ItalianName"` + Genre []genre `dgraph:"genre"` // The struct types can be nested. As long as the tags match up, all is well. + Starring []*performance `dgraph:"starring"` // Pointers to structures are fine too - that might save copying structures later. + Director []*director `dgraph:"~director.film"` // reverse edges work just like forward edges. +} + +type performance struct { + Actor *actor `dgraph:"performance.actor"` + Character *character `dgraph:"performance.character"` +} + +// Types directQuery and movieQuery help unpack query results with client.Unmarshal(). +// The Unmarshal function needs the tags to know how to unpack query results. +// With type director, Unmarshal could unpack a _uid_ and name@en, with directQuery, +// Unmarshal can unpack the whole director, or for movieQuery a slice of movie types +// from a query that returns many results. +type directQuery struct { + Root director `dgraph:"director"` +} + +type movieQuery struct { + Root []*movie `dgraph:"movie"` +} + +var ( + + // Start the crawl here. + directorSeeds = []string{"Peter Jackson", "Jane Campion", "Ang Lee", "Marc Caro", + "Jean-Pierre Jeunet", "Tom Hanks", "Steven Spielberg", + "Cherie Nowlan", "Hermine Huntgeburth", "Tim Burton", "Tyler Perry"} + + // Record what we've seen and for output at the end. + directors = make(map[uint64]*director) + actors = make(map[uint64]*actor) + characters = make(map[uint64]*character) + movies = make(map[uint64]*movie) + genres = make(map[uint64]*genre) + + edgeCount = 0 + + toVisit chan uint64 // queue of director UIDs to visit + + // Queries with variables and associated variable map. For use with SetQueryWithVariables(). + // See also https://docs.dgraph.io/query-language/#graphql-variables. + // Queries with variables allow reusing a query without having to modify + // the raw string. The query string can remain unchanged and the variable + // map changed. Used in readDirectors() and visitDirector(). + directorByNameTemplate = `{ + director(func: eq(name@en, $a)) @filter(has(director.film)) { + _uid_ + name@en + } +}` + directorByNameMap = make(map[string]string) + + directorsMoviesTemplate = `{ + movies(func: uid($a)) { + movie: director.film { + _uid_ + EnglishName: name@en + GermanName: name@de + ItalianName: name@it + starring { + performance.actor { + _uid_ + name@en + } + performance.character { + _uid_ + name@en + } + } + genre { + _uid_ + name@en + } + ~director.film { + _uid_ + name@en + } + initial_release_date + } + } +}` + directorMoviesMap = make(map[string]string) + + // A query without variables. For this one, we'll manipulate the raw + // string by print straight into %v with fmt.Sprintf(). + // Used in visitActor(). + actorByIDTemplate = `{ + actor(func: uid(%v)) { + actor.film { + performance.film { + ~director.film { + _uid_ + name@en + } + } + } + } +}` +) + +// ---------------------- Dgraph helper fns ---------------------- + +func getContext() context.Context { + return context.Background() + //return metadata.NewContext(context.Background(), metadata.Pairs("debug", "true")) +} + +// printNode is simply an example of walking through the protocol buffer response. +// It just formats the Node as text. A node has +// - Atrribute/GetAttribute() the edge that lead to this node +// - Properties/GetProperties() the scalar valued edges out of this node (each property has a name (Prop/GetProp()) and value (Value/GetValue())) +// - Children/GetChildren() the uid edges from this Node to other nodes (the edge name is recorded in the Attribute of the target) +// +// Function proto.MarshalTextString() from github.com/gogo/protobuf/proto already does this job, e.g., +// fmt.Printf("Raw Response: %+v\n", proto.MarshalTextString(resp)) +func printNode(depth int, node *protos.Node) { + + fmt.Println(strings.Repeat(" ", depth), "Atrribute : ", node.Attribute) + + // the values at this level + for _, prop := range node.GetProperties() { + fmt.Println(strings.Repeat(" ", depth), "Prop : ", prop.Prop, " Value : ", prop.Value, " Type : %T", prop.Value) + } + + for _, child := range node.Children { + fmt.Println(strings.Repeat(" ", depth), "+") + printNode(depth+1, child) + } + +} + +// Setup a request and run a query with variables. +func runQueryWithVariables(dgraphClient *client.Dgraph, query string, varMap map[string]string) (*protos.Response, error) { + req := client.Req{} + req.SetQueryWithVariables(query, varMap) + return dgraphClient.Run(getContext(), &req) +} + +// ---------------------- crawl movies ---------------------- + +// readDirectors enqueues the seed directors into the queue (toVisit) to be crawlled. +func readDirectors(directors []string, dgraphClient *client.Dgraph) { + for _, dir := range directors { + log.Print("Finding director : ", dir) + + directorByNameMap["$a"] = dir + resp, err := runQueryWithVariables(dgraphClient, directorByNameTemplate, directorByNameMap) + if err != nil { + log.Printf("Finding director %s. --- Error in getting response from server, %s.", dir, err) + } else { + + // client.Unmarshal() unpacks a query result directly into a struct. + // It's analogous to json.Unmarshal() for json files. + // + // resp.N is a slice of Nodes - one Node for each named query block + // in the query string sent to Dgraph. Each of those nodes + // has atribute "_root_" and has children for each graph node returned + // by the query. Those child nodes are labelled with the query name. + // + // Unmarshal() takes a slice of nodes and searches for children that have + // an attribute matching the tag of the given struct. + // + // In this case that's searching the children of resp.N for atributes matching + // director - thus matching query director and unmarshalling the single + // director into d. + + var d directQuery + err = client.Unmarshal(resp.N, &d) + if err == nil { + log.Print("Found ", d.Root.ID, " : ", d.Root.Name) + enqueueDirector(&d.Root) + } else { + log.Printf("Couldn't unmarshar response for %s.", dir) + log.Printf(err.Error()) + } + } + } +} + +// visitDirector is called when a director's UID is taken off the queue of +// directors to visit. Directors only get into the queue if they haven't +// been seen, so this function is called only once for each director. +func visitDirector(dir uint64, dgraphClient *client.Dgraph) { + + if edgeCount < *edgeBound { + + directorMoviesMap["$a"] = fmt.Sprint(dir) + + resp, err := runQueryWithVariables(dgraphClient, directorsMoviesTemplate, directorMoviesMap) + if err != nil { + log.Printf("Error processing director : %v.\n%s", dir, err) + return // fall over for this director, but keep trying others + } + + if len(resp.N) == 0 { + log.Printf("Found 0 movies for director : %v.\n", dir) + return + } + + // Often Unmarshal() is called at the query root to unpack the whole + // query into a struct, but that's not always required. Unmarshal() + // looks through the given node and unpacks all the children's children + // into the struct. So we can walk through the protocol buffer response + // and pick out the bit we want to unmarshal. In this instance we want to get + // all a director's movies, so we could make a struct with the director + // and a slice of their movies, but we have no other use for that struct, + // so we can unpack just the movies by walking into the protocol buffer + // and unpacking the Nodes found there. + // + // In this case: + // - resp.N is a slice of Nodes for each named query, each labeled _root_ + // - directorsMoviesTemplate has only 1 query so resp.N[0] is a Node with one child for + // each answer in the query + // - query movies asked by director UID, so there can only be one child - a node + // representing the director + // - all the directors movies are then children of that node, all labelled 'movie' because + // of the alias + // + // So if we want to unpack all the movies, we pass Unmarshal the parent Node and a structure that has a tag matching the found movies. + var movs movieQuery + err = client.Unmarshal(resp.N[0].Children, &movs) + if err != nil { + log.Print("Couldn't unmarshal response for Director ", dir) + log.Printf(err.Error()) + } + + if len(movs.Root) > 0 { + + log.Println("Found data for director : ", dir, " - ", directors[dir].Name) + + // All the actors, characters and release dates for all this director's + // movies have been unpacked into variable movs. + // Tick them off so we know not to crawl them again and so we can + // keep a count of how many edges have been found so far. + for _, m := range movs.Root { + + // We may have already seen this movie - if it has multiple + // directors and we've visited one of the other directors. + if !visitedMovie(m.ID) { + + movies[m.ID] = m + + log.Println("Movie ", m.ID, " ", m.Name) + + // A movie can have a number of directors, so we'll add one edge + // dir --- director.movie ---> m.ID + // for each one. We can't have previously visited any of the + // directors (except the one we are currently visiting) + // otherwise we would have visited this movie. + for i := range m.Director { + enqueueDirector(m.Director[i]) + edgeCount++ + } + + // There might be 3 edges for the languages and the release date, but we'd better check. + if len(m.Name) > 0 { + edgeCount++ + } + if len(m.NameDE) > 0 { + edgeCount++ + } + if len(m.NameIT) > 0 { + edgeCount++ + } + if !m.ReleaseDate.IsZero() { + edgeCount++ + } + + // A movie can have a number of genres. We'll add an edge + // m.ID --- genre ---> g.ID + // for each one, but some might be the first time we've seen this genre, so for + // those, we'll also have to add + // g.ID --- name@en ---> g.name + for _, g := range m.Genre { + edgeCount++ // for m.ID --- genre ---> g.ID + if !visitedGenre(g.ID) { + visitGenre(&g) + edgeCount++ // for g.ID --- name@en ---> g.name + } + } + + // Each movie has a number of performances, which record an actor playing the + // role of a particular character in the movie. There must be a edges + // m.ID --- starring ---> p + // p --- performance.actor ---> p.Actora.ID + // p --- performance.character ---> p.Character.ID + // But the actor may or may not have been visited so far. If they have, + // there's nothing else to do. If they haven't we'll extract all the directors + // they have worked for, add them to the director queue to be crawled and record the + // edges we'll add for the actor. + for _, p := range m.Starring { + if p.Character != nil && p.Actor != nil { + edgeCount++ // for m.ID --- starring ---> p + edgeCount++ // for p --- perfmance.film ---> m.ID + + edgeCount++ // for p --- performance.character ---> p.Character.ID + if _, ok := characters[p.Character.ID]; !ok { + characters[p.Character.ID] = p.Character + edgeCount++ // for c.ID --- name@en ---> p.Character.Name + } + + edgeCount++ // for p --- performance.actor ---> p.Actor.ID + edgeCount++ // for p.Actor.ID --- actor.film ---> p + visitActor(p.Actor, dgraphClient) + } + } + + } + + } + + } + + } +} + +// visitActor is called each time an actor is seen. Only the first time an +// actor is seen are their movies queried from Dgraph. +func visitActor(a *actor, dgraphClient *client.Dgraph) { + if !visitedActor(a.ID) { + + log.Println("visiting actor : ", a.ID, " - ", a.Name) + + actors[a.ID] = a + edgeCount++ // for a.ID --- name@en ---> a.Name + + // Find all the directors this actor has worked for + req := client.Req{} + req.SetQuery(fmt.Sprintf(actorByIDTemplate, a.ID)) + resp, err := dgraphClient.Run(getContext(), &req) + if err != nil { + log.Printf("Error processing actor : %v (%v). --- Error in getting response from server, %s", a.Name, a.ID, err) + return + } + + // Other queries have used the Unmarshal() function to put the query data + // directly into a structure. It's also possible to just grab out the results + // directly from the protocol buffer. In this case, we have to walk + // deep into the query to get the result we want, so let's just grab it directly. + // + // - resp.N should be length 1 because there was only 1 query block + // - resp.N[0].Children should be length 1 because the query asked by UID, so only one + // node can be in the answer + if len(resp.N) == 1 && len(resp.N[0].Children) == 1 { + + // We are at an actor + // For each performance in each movie they have acted in - actor.film + for _, actorsMovie := range resp.N[0].Children[0].Children { + + // At a performance. + // Really, should only be one edge to a film from a performance - performance.film + for _, actorPerformance := range actorsMovie.Children { + + // At a film. + // We've walked the graph response from actor to the films they have acted in. + // If the query had more structure, we'd have to check the Atrribute name of + // the children to check which edge we followed to get to the child. + + for _, dir := range actorPerformance.Children { + + // At a director, with a _uid_ and a name + var uid uint64 + var name string + for _, prop := range dir.Properties { + switch prop.Prop { + case "_uid_": + uid = prop.GetValue().GetUidVal() + case "name@en": + name = prop.GetValue().GetStrVal() + } + } + enqueueDirector(&director{uid, name}) + } + } + } + } + } +} + +func crawl(dgraphClient *client.Dgraph) { + done := false + + for !done { + select { + case dirID := <-toVisit: + visitDirector(dirID, dgraphClient) + default: + done = true + } + } +} + +func visitGenre(g *genre) { + genres[g.ID] = g +} + +func visitedActor(actorID uint64) bool { + _, ok := actors[actorID] + return ok +} + +func visitedMovie(movID uint64) bool { + _, ok := movies[movID] + return ok +} + +func visitedGenre(genID uint64) bool { + _, ok := genres[genID] + return ok +} + +func visitedDirector(dirID uint64) bool { + _, ok := directors[dirID] + return ok +} + +func enqueueDirector(dir *director) { + if !visitedDirector(dir.ID) { + directors[dir.ID] = dir + edgeCount++ // For dir.ID --- name ---> dir.Name + go func() { toVisit <- dir.ID }() + } +} + +// ---------------------- main---------------------- + +func main() { + log.SetFlags(log.LstdFlags | log.Lshortfile) + flag.Parse() + if !flag.Parsed() { + log.Fatal("Unable to parse flags") + } + + toVisit = make(chan uint64) + + conn, err := grpc.Dial(*dgraph, grpc.WithInsecure()) + if err != nil { + log.Fatal(err) + } + defer conn.Close() + + // The Dgraph client needs a directory in which to write its blank node maps. + clientDir, err := ioutil.TempDir("", "client_") + if err != nil { + log.Fatal(err) + } + defer os.RemoveAll(clientDir) + + // A DgraphClient made from a succesful connection. All calls to the client and thus the backend go through this. + // We won't be doing any batching with this client, just queries, so we can ignore the BatchMutationOptions. + dgraphClient := client.NewDgraphClient([]*grpc.ClientConn{conn}, client.DefaultOptions, clientDir) + defer dgraphClient.Close() + + // Fill up the director queue with directors + readDirectors(directorSeeds, dgraphClient) + + // The seed directors are set up, so we can start to crawl. + crawl(dgraphClient) + + // Write all the crawled info out to gzipped rdf. We'll write every UID as a blank node just by prefixing every UID with _:BN. + + f, err := os.Create(*outfile) + if err != nil { + log.Fatalf("Couldn't open file %s", err) + } + defer f.Close() + + toFile := gzip.NewWriter(f) + defer toFile.Close() + + totalEdges := 0 + + // RDF triples look like + // source-node <edge-name> target-node . + // or + // source-node <edge-name> scalar-value . + + toFile.Write([]byte("\n\t\t# -------- directors --------\n\n")) + for _, dir := range directors { + toFile.Write([]byte(fmt.Sprintf("\t\t_:BN%v <name> \"%v\"@en .\n", dir.ID, dir.Name))) + totalEdges++ + } + log.Printf("Wrote %v directors to %v", len(directors), *outfile) + + toFile.Write([]byte("\n\t\t# -------- actors --------\n\n")) + for _, actor := range actors { + toFile.Write([]byte(fmt.Sprintf("\t\t_:BN%v <name> \"%v\"@en .\n", actor.ID, actor.Name))) + totalEdges++ + } + log.Printf("Wrote %v actors to %v", len(actors), *outfile) + + toFile.Write([]byte("\n\t\t# -------- genres --------\n\n")) + for _, genre := range genres { + toFile.Write([]byte(fmt.Sprintf("\t\t_:BN%v <name> \"%v\"@en .\n", genre.ID, genre.Name))) + totalEdges++ + } + log.Printf("Wrote %v genres to %v", len(genres), *outfile) + + toFile.Write([]byte("\n\t\t# -------- movies --------\n\n")) + + for _, movie := range movies { + if movie.Name != "" { + toFile.Write([]byte(fmt.Sprintf("\t\t_:BN%v <name> \"%v\"@en .\n", movie.ID, movie.Name))) + totalEdges++ + } + if movie.NameDE != "" { + toFile.Write([]byte(fmt.Sprintf("\t\t_:BN%v <name> \"%v\"@de .\n", movie.ID, movie.NameDE))) + totalEdges++ + } + if movie.NameIT != "" { + toFile.Write([]byte(fmt.Sprintf("\t\t_:BN%v <name> \"%v\"@it .\n", movie.ID, movie.NameIT))) + totalEdges++ + } + + for _, dir := range movie.Director { + toFile.Write([]byte(fmt.Sprintf("\t\t_:BN%v <director.film> _:BN%v .\n", dir.ID, movie.ID))) + totalEdges++ + } + + for _, genre := range movie.Genre { + toFile.Write([]byte(fmt.Sprintf("\t\t_:BN%v <genre> _:BN%v .\n", movie.ID, genre.ID))) + totalEdges++ + } + + toFile.Write([]byte(fmt.Sprintf("\t\t_:BN%v <initial_release_date> \"%v\" .\n", movie.ID, movie.ReleaseDate.Format(time.RFC3339)))) + totalEdges++ + + for _, p := range movie.Starring { + if p.Character != nil && p.Actor != nil { + pBlankNode := uuid.NewV4() + + toFile.Write([]byte(fmt.Sprintf("\t\t_:BN%v <starring> _:BN%v .\n", movie.ID, pBlankNode))) + toFile.Write([]byte(fmt.Sprintf("\t\t_:BN%v <performance.film> _:BN%v .\n", pBlankNode, movie.ID))) + + toFile.Write([]byte(fmt.Sprintf("\t\t_:BN%v <performance.actor> _:BN%v .\n", pBlankNode, p.Actor.ID))) + toFile.Write([]byte(fmt.Sprintf("\t\t_:BN%v <actor.film> _:BN%v .\n", p.Actor.ID, pBlankNode))) + + toFile.Write([]byte(fmt.Sprintf("\t\t_:BN%v <performance.character> _:BN%v .\n", pBlankNode, p.Character.ID))) + toFile.Write([]byte(fmt.Sprintf("\t\t_:%v <name> \"%v\"@en .\n", p.Character.ID, p.Character.Name))) + totalEdges += 6 + } + } + toFile.Write([]byte(fmt.Sprintln())) + } + log.Printf("Wrote %v movies to %v", len(movies), *outfile) + + log.Printf("Wrote %v edges in total to %v", totalEdges, *outfile) +} diff --git a/wiki/resources/examples/goclient/crawlermutations/.gitignore b/wiki/resources/examples/goclient/crawlermutations/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..cf574d61a854c2ec48fb82d77030532b2fc546c0 --- /dev/null +++ b/wiki/resources/examples/goclient/crawlermutations/.gitignore @@ -0,0 +1,2 @@ +/crawler + diff --git a/wiki/resources/examples/goclient/crawlermutations/crawler.go b/wiki/resources/examples/goclient/crawlermutations/crawler.go new file mode 100644 index 0000000000000000000000000000000000000000..6611fdf5fb411cd579624cf75b299214d04e79e4 --- /dev/null +++ b/wiki/resources/examples/goclient/crawlermutations/crawler.go @@ -0,0 +1,726 @@ +/* + * Copyright 2016 Dgraph Labs, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + + +*** Check out the blog post about this code : https://open.dgraph.io/post/client0.8.0 *** + + +This program is an example of how to use the Dgraph go client. It is one of two example crawlers. +The other, crawlerRDF, is more focused on queries in the Dgraph client. Look there if you want to +learn about queries and Unmarshal(). This crawler is about mutations using the client interface. + +The Dgraph client interface has docs here : https://godoc.org/github.com/dgraph-io/dgraph/client + + + +When we made our tour (https://tour.dgraph.io/) we needed a dataset users could load quickly, +but with enough complexity to demostrate interesting queries. We decided a subset of +our 21million dataset was just right. But we can't just take the first n-lines from the +input file - who knows what connections in the graph we'd get or miss if we did that. It's +a graph; so the best way to make a subset is to crawl it. + +This program crawls a Dgraph database loaded with the 21million movie dataset; data available +here : https://github.com/dgraph-io/benchmarks/tree/master/data. At Dgraph we use this dataset +for the examples in our docs. There's instructions on starting up Dgraph and loading this +dataset in our docs here : https://docs.dgraph.io/get-started/. + +Given a loose bound on the number of edges in the output graph (edgeBound), this crawler crawls by +movies, keeping a queue of unvisited movies. For each movie it takes off the queue, it +gets all the info for the movie and then queues all movies for all actors in the movie. The crawl +stops when the edge bound is exceeded (though crawlers complete the their current movie, so it will +blow the bound by a bit). + +This crawler crawls one Dgraph instance and stores directly to another instance. So to run it, +you'll need a source Dgraph instance (or cluster) loaded with the 21million data and a target +instance (or cluster) to load into. + + +build with + +go build crawler.go + +run with --help to see the options + +Depending on where you've started the Dgraph instances, you might run with something like: + +./crawler.go --source "<somehost>:9080,<someotherhost>:9080" --target "127.0.0.1:9080" --edges 500000 --crawlers 10 > crawl.log 2>&1 + +The ending '> crawl.log 2>&1' redirects logging output to a file. + +*** Check out the blog post about this code : https://open.dgraph.io/post/client0.8.0 *** + + +*/ + +package main + +import ( + "context" + "flag" + "fmt" + "io/ioutil" + "log" + "os" + "strings" + "sync" + "sync/atomic" + "time" + + "google.golang.org/grpc" + //"google.golang.org/grpc/metadata" // for debug mode + //"github.com/gogo/protobuf/proto" // for with fmt.Printf("Raw Response: %+v\n", proto.MarshalTextString(resp)) + + "github.com/dgraph-io/dgraph/client" + "github.com/dgraph-io/dgraph/protos" +) + +var ( + dgraphSource = flag.String("source", "127.0.0.1:9080", "Source Dgraph gRPC server addresses (comma separated)") + dgraphTarget = flag.String("target", "127.0.0.1:9081", "Target Dgraph gRPC server addresses (comma separated)") + edgeBound = flag.Int("edges", 50000, "Stop crawling after we've made this many edges") + crawlers = flag.Int("crawlers", 1, "Number of concurrent crawlers") +) + +// Dgraph will unpack queries into these structures with client.Unmarshal(), +// we just need to say what goes where. +// +// See how Unmarshal is used in readMovie() and visitMovie(). Godocs and smaller examples are at +// https://godoc.org/github.com/dgraph-io/dgraph/client#Unmarshal +// +// See also our crawlerRDF example for more description about Unmarshal and structs. +type namedNode struct { + ID uint64 `dgraph:"_uid_"` + Name string `dgraph:"name@en"` +} + +type movie struct { + ReleaseDate time.Time `dgraph:"initial_release_date"` + ID uint64 `dgraph:"_uid_"` + Name string `dgraph:"EnglishName"` + NameDE string `dgraph:"GermanName"` + NameIT string `dgraph:"ItalianName"` + Genres []*namedNode `dgraph:"genre"` + Starring []*performance `dgraph:"starring"` + Directors []*namedNode `dgraph:"~director.film"` +} + +type performance struct { + Actor *namedNode `dgraph:"performance.actor"` + Character *namedNode `dgraph:"performance.character"` +} + +// A helper struct for Unmarshal in readMovies() and visitMovie(). In visitMovie we unpack the +// query into the whole struct, but Unmarshal() doesn't need to fill the whole +// struct. The query in readMovies() only fills the ID. Another option in readMovies() would +// be reading into a namedNode or just grabbing the UID like in visitActor(). +type movieQuery struct { + Root *movie `dgraph:"movie"` +} + +// Tick off the things we have seen in our crawl so far, so we only create each movie, director, +// actor, etc. once in the target. +type savedNodes struct { + nodes map[uint64]client.Node // source UID -> target Node + sync.RWMutex // many concurrent crawlers will need safe access to the map +} + +var ( + + // Start the crawl here. + movieSeeds = []string{"Blade Runner"} + + // Queue of movies to visit. + toVisit = make(chan uint64, *crawlers) + + // Movies we've seen so far in the crawl. If a movie is ticked as true here, a crawler has + // seen that it exists and added it to toVisit. A movie is only ever added once to toVisit. + movies = make(map[uint64]bool) + movMux sync.Mutex + + // Actors can also be directors, so we need to keep track of them together. + people = savedNodes{nodes: make(map[uint64]client.Node)} + + // The same character in two different movies is the same character node in the graph - the + // node for character Harry Potter is the same for Daniel Radcliffe in all Harry Potter movies + // and even for Toby Papworth who played the baby Harry. So as well as making a single node + // for Daniel Radcliffe that's used for all his roles, we also need to ensure we link the + // characters correctly. + characters = savedNodes{nodes: make(map[uint64]client.Node)} + + // Genres seen. + genres = savedNodes{nodes: make(map[uint64]client.Node)} + + edgeCount int32 // = 0 + + // To signal crawlers to stop when all is done. + done = make(chan interface{}) + + wg sync.WaitGroup // Crawlers signal main go routine as they exit. + + // Queries with variable and associated variable map. For use with SetQueryWithVariables(). + // See also https://docs.dgraph.io/query-language/#graphql-variables. + // Queries with variables allow reusing a query without having to modify + // the raw string. The query string can remain unchanged and the variable + // map changed. + movieByNameTemplate = `{ + movie(func: eq(name@en, $a)) @filter(has(genre)) { + _uid_ + } +}` + movieByNameMap = make(map[string]string) + + movieByIDTemplate = `{ + movie(func: uid($a)) { + _uid_ + EnglishName: name@en + GermanName: name@de + ItalianName: name@it + starring { + performance.actor { + _uid_ + name@en + } + performance.character { + _uid_ + name@en + } + } + genre { + _uid_ + name@en + } + ~director.film { + _uid_ + name@en + } + initial_release_date + } +}` + movieByIDMap = make(map[string]string) + + // A query without variables. For this one, we'll manipulate the raw string by printing + // straight into %v with fmt.Sprintf(). + actorByIDTemplate = `{ + actor(func: uid(%v)) { + actor.film { + performance.film { + _uid_ + } + } + } +}` +) + +func getContext() context.Context { + return context.Background() + //return metadata.NewContext(context.Background(), metadata.Pairs("debug", "true")) +} + +// Setup a request and run a query with variables. +func runQueryWithVariables(dgraphClient *client.Dgraph, query string, varMap map[string]string) (*protos.Response, error) { + req := client.Req{} + req.SetQueryWithVariables(query, varMap) + return dgraphClient.Run(getContext(), &req) +} + +// ---------------------- crawl movies ---------------------- + +// readMovies enqueues the seed movies into the queue (toVisit) ready to be crawlled. +func readMovies(movies []string, dgraphClient *client.Dgraph) { + for _, mov := range movies { + log.Print("Finding movie : ", mov) + + movieByNameMap["$a"] = mov + resp, err := runQueryWithVariables(dgraphClient, movieByNameTemplate, movieByNameMap) + if err != nil { + log.Printf("Finding movie %s. --- Error in getting response from server, %s.", mov, err) + // But still continue if we fail with some movies. + } else { + var m movieQuery + err = client.Unmarshal(resp.N, &m) + if err == nil { + log.Print("Found Movie ", m.Root.ID) + enqueueMovie(m.Root.ID) + } else { + log.Printf("Couldn't unmarshal response for %s.", mov) + log.Printf(err.Error()) + } + } + } +} + +// ensureNamedNodes makes sure that the given named node (from the source) is created in the +// target Dgraph instance and ticked off in our source UID -> target node map. If anything goes +// wrong, it just returns an error - and hasn't either saved in the target instance or in the map. +// +// Some bookkeeping is required in this crawl to ensure that movies are only visited once and +// that each actor is queried for only once. Example movielensbatch shows how the client can +// reduce this burden by associating a label to nodes. +func ensureNamedNode(n *namedNode, saved *savedNodes, target *client.Dgraph) error { + + saved.RLock() + if _, ok := saved.nodes[n.ID]; !ok { // optimisitic first read + + // read failed, so we need a write lock to update + saved.RUnlock() + saved.Lock() + defer saved.Unlock() + + // but another go routine might have written in the meantime + if _, ok := saved.nodes[n.ID]; !ok { + + node, err := target.NodeBlank("") + if err != nil { + return err + } + + req := client.Req{} + e := node.Edge("name") + e.SetValueString(n.Name) + req.Set(e) + + _, err = target.Run(context.Background(), &req) + if err != nil { + return err + } + + saved.nodes[n.ID] = node + } + } else { + // value was already there + saved.RUnlock() + } + return nil +} + +// Protect concurrent reads. +func getFromSavedNode(saved *savedNodes, ID uint64) (n client.Node, ok bool) { + saved.RLock() + n, ok = saved.nodes[ID] + saved.RUnlock() + return +} + +// visitMovie is called when a movies's UID is taken off the queue. It queries all the data +// for the movie and writes to the target. It also adds any movies of actors in this movie +// to the queue of movies to crawl. +func visitMovie(movieID uint64, source *client.Dgraph, target *client.Dgraph) { + + if atomic.LoadInt32(&edgeCount) < int32(*edgeBound) { + + log.Print("Processing movie : ", movieID) + + movieByIDMap["$a"] = fmt.Sprint(movieID) + + resp, err := runQueryWithVariables(source, movieByIDTemplate, movieByIDMap) + if err != nil { + log.Printf("Error processing movie : %v.\n%s", movieID, err) + return // fall over for this movie, but keep trying others + } + // fmt.Printf("Raw Response: %+v\n", proto.MarshalTextString(resp)) + + var mq movieQuery + err = client.Unmarshal(resp.N, &mq) + if err != nil { + log.Print("Couldn't unmarshal response for movie ", movieID) + log.Printf(err.Error()) + return + } + m := mq.Root + + log.Println("Found data for movie : ", m.ID, " - ", m.Name) + + var edgesToAdd int32 + + // req will store all the edges for this movie (director names, actor names, etc are + // committed separately by ensureNamedNode()). We'll committ all at once or fail + // for the whole movie. + req := client.Req{} + + // Every edge we are going to committ will be stored in here. Once we've called + // req.Set(e), it's safe to reuse e for a different edge. + var e client.Edge + + // Getting a blank node with an empty string just gets a new node and doesn't record + // a blank node name to node map. Here, we don't need the blank nodes outside of this + // function, so no need to map them for later use. + mnode, err := target.NodeBlank("") + if err != nil { + log.Println("Failing for movie : ", m.ID, " - ", m.Name) + log.Println(err) + return + } + + if m.Name != "" { + e = mnode.Edge("name") + err = e.SetValueStringWithLang(m.Name, "en") + if err != nil { + log.Println("Failing for movie : ", m.ID, " - ", m.Name) + log.Println(err) + return + } + err = req.Set(e) + if err != nil { + log.Println("Failing for movie : ", m.ID, " - ", m.Name) + log.Println(err) + return + } + edgesToAdd++ + } + if m.NameDE != "" { + e = mnode.Edge("name") + if e.SetValueStringWithLang(m.NameDE, "de") == nil { + req.Set(e) + edgesToAdd++ + } // ignore this edge if error + } + if m.NameIT != "" { + e = mnode.Edge("name@it") + if e.SetValueStringWithLang(m.NameIT, "it") == nil { + req.Set(e) + edgesToAdd++ + } + } + if !m.ReleaseDate.IsZero() { + e = mnode.Edge("initial_release_date") + if e.SetValueDatetime(m.ReleaseDate) == nil { + req.Set(e) + edgesToAdd++ + } + } + + // A movie can have a number of directors, so we'll add one edge for each one. + // If we haven't seen the director before, add their name too and update the + // directors map. + edgesToAdd += int32(len(m.Directors)) + for _, d := range m.Directors { + err = ensureNamedNode(d, &people, target) + if err != nil { + log.Println("Failing for movie : ", m.ID, " - ", m.Name) + log.Println(err) + return + } + + dnode, _ := getFromSavedNode(&people, d.ID) + e = dnode.ConnectTo("director.film", mnode) + req.Set(e) + } + + // A movie can have a number of genres. We'll add an edge for each one, but, + // first, ensure that each genre is added. + edgesToAdd += int32(len(m.Genres)) + for _, g := range m.Genres { + err = ensureNamedNode(g, &genres, target) + if err != nil { + log.Println("Failing for movie : ", m.ID, " - ", m.Name) + log.Println(err) + return + } + + gnode, _ := getFromSavedNode(&genres, g.ID) + e = mnode.ConnectTo("genre", gnode) + req.Set(e) + } + + // The movies for all actors in this movie. After we're done, we'll enqueue all of these. + newMoviesToVisit := make([]uint64, 1000) + + // Each movie has a number of performances, which record an actor playing the role of a + // particular character in the movie. We need to add edges + // m.ID --- starring ---> p + // p --- performance.actor ---> actor + // p --- performance.character ---> character + // for every character in the movie. And add the actors and characters, if they haven't + // been added yet. + for _, p := range m.Starring { + if p.Actor != nil && p.Character != nil { + edgesToAdd++ // for m.ID --- starring ---> p + pnode, err := target.NodeBlank("") + if err != nil { + log.Println("Failing for movie : ", m.ID, " - ", m.Name) + log.Println(err) + return + } + e = mnode.ConnectTo("starring", pnode) + req.Set(e) + + edgesToAdd++ // for p --- performance.character ---> p.character + err = ensureNamedNode(p.Character, &characters, target) + if err != nil { + log.Println("Failing for movie : ", m.ID, " - ", m.Name) + log.Println(err) + return + } + cnode, _ := getFromSavedNode(&characters, p.Character.ID) + e = pnode.ConnectTo("performance.character", cnode) + req.Set(e) + + // Only get the movies of this actor if they haven't been seen before. + if _, ok := getFromSavedNode(&people, p.Actor.ID); !ok { + newMoviesToVisit = append(newMoviesToVisit, visitActor(p.Actor, source)...) + } + + edgesToAdd++ // for p --- performance.actor ---> p.Actora.ID + err = ensureNamedNode(p.Actor, &people, target) + if err != nil { + log.Println("Failing for movie : ", m.ID, " - ", m.Name) + log.Println(err) + return + } + anode, _ := getFromSavedNode(&people, p.Actor.ID) + e = pnode.ConnectTo("performance.actor", anode) + req.Set(e) + } + } + + // If we got this far, all the people, genres and characters have been saved to the + // store and req contains Set mutations for all the edges in this movie. + _, err = target.Run(getContext(), &req) + if err != nil { + // Not worrying about potential errors here, just ignore this movie if Run fails + } else { + // If all those edges were saved, safely increase the edge count + atomic.AddInt32(&edgeCount, edgesToAdd) + log.Print("Committed movie : ", m.ID, " - ", m.Name) + } + + for _, id := range newMoviesToVisit { + enqueueMovie(id) + } + + } else { + log.Print("Too many edges. Ignoring movie : ", movieID) + } +} + +// visitActor is called each time an actor is seen. Try to only run it once for each actor. But +// if multiple go routines find the same actor at the same time, we might get through the check, +// but enqueueMovie() is safe, so it's just a wasted query. +func visitActor(a *namedNode, dgraphClient *client.Dgraph) (result []uint64) { + + log.Println("visiting actor : ", a.ID, " - ", a.Name) + + // Find all the movies this actor has worked on + req := client.Req{} + req.SetQuery(fmt.Sprintf(actorByIDTemplate, a.ID)) + resp, err := dgraphClient.Run(getContext(), &req) + if err != nil { + log.Printf("Error processing actor : %v (%v). --- Error in getting response from server, %s", a.Name, a.ID, err) + return result + } + + // - resp.N should be length 1 because there was only 1 query block + // - resp.N[0].Children should be length 1 because the query asked by UID, so only one node + // can be in the answer + if len(resp.N) == 1 && len(resp.N[0].Children) == 1 { + + // We are at an actor + // For each performance in each movie they have acted in - actor.film + for _, actorsMovie := range resp.N[0].Children[0].Children { + + // At a performance. + // Really, should only be one edge to a film from a performance - performance.film + for _, actorPerformance := range actorsMovie.Children { + + // At a film. + // We've walked the graph response from actor to the films they have acted in. + + var uid uint64 + + for _, prop := range actorPerformance.Properties { + switch prop.Prop { + case "_uid_": + uid = prop.GetValue().GetUidVal() + } + } + result = append(result, uid) + } + } + } + return result +} + +// Add the movie to the queue of movies to visit if we haven't blown the edge bound. If we have +// gone over the edge bound, signal all crawlers to exit. +func enqueueMovie(movID uint64) { + movMux.Lock() + defer movMux.Unlock() + + // We have to lock here to protect against visiting the same movie multiple times. + // So we can safely close done if it hasn't been closed before. + // + // We can't close toVisit as the exit signal because there is no guarantee that the spawned + // go routines that write to it have done so, even if they were started when safe to do so. + + if atomic.LoadInt32(&edgeCount) > int32(*edgeBound) { + select { + case <-done: + // noop - already closed + default: + log.Print("Sending exit signal.") + close(done) + } + return + } + + if _, ok := movies[movID]; !ok { + movies[movID] = true + go func() { toVisit <- movID }() + } +} + +func startCrawler(source *client.Dgraph, target *client.Dgraph) { + + defer wg.Done() // no matter what happens signal my exit + + for { + select { + case movID := <-toVisit: + visitMovie(movID, source, target) + case <-done: + return + } + } +} + +func crawl(numCrawlers int, source *client.Dgraph, target *client.Dgraph) { + + wg.Add(numCrawlers) + + for i := 0; i < numCrawlers; i++ { + go startCrawler(source, target) + } + + wg.Wait() + + // After wg.Wait() is done, all the reading and writing is done, so it's safe to exit. +} + +// Not quite higher-order compose. +// Compose together the exit functions and log any errors. +func compose(f func(), g func() error) func() { + return func() { + err := g() + if err != nil { + log.Print("Shutdown not clean : ", err) + } + f() + } +} + +// When connecting to a Dgraph client you can specify a slice of grpc connections. That way +// you can open multiple connections - even connections to multiple machines if you are running +// in a cluster - and the client will spread your requests accross the connections. +func connect(dgraphs []string) (*client.Dgraph, func(), error) { + + // A function to do all the clean up from this connection. + // If we fail partway through, call this do undo everything and return the error. + f := func() {} + + var conns []*grpc.ClientConn + for _, host := range dgraphs { + conn, err := grpc.Dial(host, grpc.WithInsecure()) + if err != nil { + f() + return nil, nil, err + } + conns = append(conns, conn) + + f = compose(f, conn.Close) + } + + // The Dgraph client needs a directory in which to write its blank node and XID maps. + clientDir, err := ioutil.TempDir("", "client_") + if err != nil { + f() + return nil, nil, err + } + f = compose(f, func() error { return os.RemoveAll(clientDir) }) + + // A DgraphClient made from a slice of succeful connections. All calls to the client + // and thus the backend(s) go through this. We won't be doing any batching with these + // clients, just queries and running mutations, so we can ignore the BatchMutationOptions. + dg := client.NewDgraphClient(conns, client.DefaultOptions, clientDir) + f = compose(f, dg.Close) + + return dg, f, nil +} + +// ---------------------- main---------------------- + +func main() { + log.SetFlags(log.LstdFlags | log.Lshortfile) + flag.Parse() + if !flag.Parsed() { + log.Fatal("Unable to parse flags") + } + + srcHostList := strings.Split(*dgraphSource, ",") + if len(srcHostList) == 0 { + log.Fatal("No source Dgraph given") + } + dgraphSource, srcCleanup, err := connect(srcHostList) + if err != nil { + log.Fatal(err) + } + defer srcCleanup() + + destHostList := strings.Split(*dgraphTarget, ",") + if len(destHostList) == 0 { + log.Fatal("No target Dgraph given") + } + dgraphTarget, trgtCleanup, err := connect(destHostList) + if err != nil { + log.Fatal(err) + } + defer trgtCleanup() + + // Add a schema for the target Dgraph instance. The original schema has edges for + // performance.film (the reverse of starrting) + // performance.actor (the reverse of actor.film) + // For this example, we'll just rely on Dgraph to create the reverse edges. + req := client.Req{} + req.SetQuery(`mutation { + schema { + director.film : uid @reverse @count . + actor.film : uid @reverse @count . + genre : uid @reverse @count . + starring : uid @reverse @count . + initial_release_date : dateTime @index . + name : string @index(term, exact, fulltext, trigram) . + } +}`) + _, err = dgraphTarget.Run(getContext(), &req) + if err != nil { + log.Fatal("Couldn't set target schema.\n", err) + } + + // Fill up the toVisit queue with movie IDs + readMovies(movieSeeds, dgraphSource) + + crawl(*crawlers, dgraphSource, dgraphTarget) + + log.Printf("Wrote %v people (actors and directors).", len(people.nodes)) + log.Printf("Wrote %v movies.", len(movies)) + log.Printf("Wrote %v characters.", len(characters.nodes)) + log.Printf("Wrote %v genres.", len(genres.nodes)) + + // More edges than this will end up in the store if the schema has @reverse edges. + log.Printf("Wrote %v edges in total.", edgeCount) + +} diff --git a/wiki/resources/examples/goclient/movielensbatch/.gitignore b/wiki/resources/examples/goclient/movielensbatch/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..8b40704e2c8a3ac8d70011ddf276f0d8c9522ac2 --- /dev/null +++ b/wiki/resources/examples/goclient/movielensbatch/.gitignore @@ -0,0 +1,2 @@ +/mlbatch +/movielensbatch diff --git a/wiki/resources/examples/goclient/movielensbatch/mlbatch.go b/wiki/resources/examples/goclient/movielensbatch/mlbatch.go new file mode 100644 index 0000000000000000000000000000000000000000..5583a8a95ca08e044080acb75687492580fd6972 --- /dev/null +++ b/wiki/resources/examples/goclient/movielensbatch/mlbatch.go @@ -0,0 +1,320 @@ +/* + * Copyright 2016 Dgraph Labs, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + + +*** Check out the blog post about this code : https://open.dgraph.io/post/client0.8.0 *** + +Go routines concurrently read from text input files and batch writes using the go client. + +Another version of this program outputed gzipped RDF +https://github.com/dgraph-io/benchmarks/tree/master/movielens/conv100k +It's output was used in blog posts about building recommendation systems in Dgraph +https://open.dgraph.io/post/recommendation/ +https://open.dgraph.io/post/recommendation2/ + + +To run the program: + +- build with + +go build mlbatch.go + +- start a dgraph instance, e.g for default options + +dgraph + +- run in a directory with the movielens data unpacked + +./mlbatch + +Use --help on dgraph or mlbatch to see the options - dgraph's --grpc_port must match mlbatch's --d +and the unpacked movieLens data must be in dir ./ml-100k or --genre, etc given as options. + +You can add a schema with + +mutation { + schema { + name: string @index(term, exact) . + rated: uid @reverse @count . + genre: uid @reverse . + } +} + +and run queries like + +{ + q(func: eq(name, "Toy Story (1995)")) { + name + genre { + name + } + count(~rated) + } +} + +or see the queries at +https://open.dgraph.io/post/recommendation/ and +https://open.dgraph.io/post/recommendation2/ +(though your UIDs will be different) + + + +*** Check out the blog post about this code : https://open.dgraph.io/post/client0.8.0 *** + +*/ + +package main + +import ( + "bufio" + "flag" + "io" + "io/ioutil" + "log" + "os" + "strconv" + "strings" + "sync" + + "google.golang.org/grpc" + + "github.com/dgraph-io/dgraph/client" + "github.com/dgraph-io/dgraph/x" +) + +var ( + dgraph = flag.String("d", "127.0.0.1:9080", "Dgraph gRPC server address") + concurrent = flag.Int("c", 10, "Number of concurrent requests to make to Dgraph") + numRdf = flag.Int("m", 100, "Number of RDF N-Quads to send as part of a mutation.") + + genre = flag.String("genre", "ml-100k/u.genre", "") + data = flag.String("rating", "ml-100k/u.data", "") + users = flag.String("user", "ml-100k/u.user", "") + movie = flag.String("movie", "ml-100k/u.item", "") +) + +func main() { + + log.SetFlags(log.LstdFlags | log.Lshortfile) + flag.Parse() + if !flag.Parsed() { + log.Fatal("Unable to parse flags") + } + + conn, err := grpc.Dial(*dgraph, grpc.WithInsecure()) + x.Check(err) + defer conn.Close() + + // The Dgraph client needs a directory in which to write its blank node maps. + // We'll use blank nodes below to record users and movies, when we need them again + // we can look them up in the client's map and get the right node without having + // to record or issue a query. + // + // The blank node map records blank-node-name -> Node, so everytime in the load we refer + // to a node we can grab it from the map. These names aren't presisted in Dgraph (if we + // wanted that we'd use an XID). + clientDir, err := ioutil.TempDir("", "client_") + x.Check(err) + defer os.RemoveAll(clientDir) + + // The client builds Pending concurrent batchs each of size Size and submits to the server + // as each batch fills. + bmOpts := client.BatchMutationOptions{ + Size: *numRdf, + Pending: *concurrent, + PrintCounters: true, + } + dgraphClient := client.NewDgraphClient([]*grpc.ClientConn{conn}, bmOpts, clientDir) + defer dgraphClient.Close() + + // We aren't writing any schema here. You can load the schema at + // https://github.com/dgraph-io/benchmarks/blob/master/movielens/movielens.schema + // using draphloader (--s option with no data file), or by running a mutation + // mutation { schema { <content of schema file> } } + // dgraphloader function processSchemaFile() also shows an example of how to load + // a schema file using the client. + + gf, err := os.Open(*genre) + x.Check(err) + defer gf.Close() + uf, err := os.Open(*users) + x.Check(err) + defer gf.Close() + df, err := os.Open(*data) + x.Check(err) + defer df.Close() + mf, err := os.Open(*movie) + x.Check(err) + defer mf.Close() + + var wg sync.WaitGroup + wg.Add(4) + + // The blank node names are used accross 4 go routines. It doesn't mater which go routine + // uses the node name first - a "user<userID>" node may be first used in the go routine reading + // users, or the one setting ratings - the Dgraph client ensures that all the routines are + // talking about the same nodes. So no matter what the creation order, or the order the client + // submits the batches in the background, the graph is connected properly. + + go func() { + defer wg.Done() + + // Each line in genre file looks like + // genre-name|genreID + // We'll use a blank node named "genre<genreID>" to identify each genre node + br := bufio.NewReader(gf) + log.Println("Reading genre file") + for { + line, err := br.ReadString('\n') + if err != nil && err == io.EOF { + break + } + line = strings.Trim(line, "\n") + csv := strings.Split(line, "|") + if len(csv) != 2 { + continue + } + + n, err := dgraphClient.NodeBlank("genre" + csv[1]) + x.Check(err) + + e := n.Edge("name") + x.Check(e.SetValueString(csv[0])) + x.Check(dgraphClient.BatchSet(e)) + } + }() + + go func() { + defer wg.Done() + + // Each line in the user file looks like + // userID|age|genre|occupation|ZIPcode + // We'll use a blank node named "user<userID>" to identify each user node + br := bufio.NewReader(uf) + log.Println("Reading user file") + for { + line, err := br.ReadString('\n') + if err != nil && err == io.EOF { + break + } + line = strings.Trim(line, "\n") + csv := strings.Split(line, "|") + if len(csv) != 5 { + continue + } + + n, err := dgraphClient.NodeBlank("user" + csv[0]) + x.Check(err) + + e := n.Edge("age") + age, err := strconv.ParseInt(csv[1], 10, 32) + x.Check(err) + x.Check(e.SetValueInt(age)) + x.Check(dgraphClient.BatchSet(e)) + + e = n.Edge("gender") + x.Check(e.SetValueString(csv[2])) + x.Check(dgraphClient.BatchSet(e)) + + e = n.Edge("occupation") + x.Check(e.SetValueString(csv[3])) + x.Check(dgraphClient.BatchSet(e)) + + e = n.Edge("zipcode") + x.Check(e.SetValueString(csv[4])) + x.Check(dgraphClient.BatchSet(e)) + } + }() + + go func() { + defer wg.Done() + + // The lines of the movie file look like + // movieID|movie-name|date||imdb-address|genre0?|genre1?|...|genre18? + // We'll use "movie<movieID>" as the blank node name + br := bufio.NewReader(mf) + log.Println("Reading movies file") + for { + line, err := br.ReadString('\n') + if err != nil && err == io.EOF { + break + } + line = strings.Trim(line, "\n") + csv := strings.Split(line, "|") + if len(csv) != 24 { + continue + } + + n, err := dgraphClient.NodeBlank("movie" + csv[0]) + x.Check(err) + + e := n.Edge("name") + x.Check(e.SetValueString(csv[1])) + x.Check(dgraphClient.BatchSet(e)) + + // 1 means the movie has the corresponding genre + for i := 5; i < 24; i++ { + if csv[i] == "0" { + continue + } + + g, err := dgraphClient.NodeBlank("genre" + strconv.Itoa(i-5)) + x.Check(err) + e = n.ConnectTo("genre", g) + x.Check(dgraphClient.BatchSet(e)) + } + } + }() + + go func() { + defer wg.Done() + + // Each line in the rating file looks like + // userID movieID rating timestamp + br := bufio.NewReader(df) + log.Println("Reading rating file") + for { + line, err := br.ReadString('\n') + if err != nil && err == io.EOF { + break + } + line = strings.Trim(line, "\n") + csv := strings.Split(line, "\t") + if len(csv) != 4 { + continue + } + + u, err := dgraphClient.NodeBlank("user" + csv[0]) + x.Check(err) + + m, err := dgraphClient.NodeBlank("movie" + csv[1]) + x.Check(err) + + e := u.ConnectTo("rated", m) + e.AddFacet("rating", csv[2]) + x.Check(dgraphClient.BatchSet(e)) + } + }() + + wg.Wait() + + // This must be called at the end of a batch to ensure all batched mutations are sent to the store. + dgraphClient.BatchFlush() + + log.Println("Finised.") +}