github.com/dgraph-io/dgraph@v1.2.8/wiki/content/tips/index.md (about) 1 +++ 2 title = "GraphQL+-: Tips and Tricks" 3 +++ 4 5 ## Get Sample Data 6 7 Use the `has` function to get some sample nodes. 8 9 {{< runnable >}} 10 { 11 result(func: has(director.film), first: 10) { 12 uid 13 expand(_all_) 14 } 15 } 16 {{< /runnable >}} 17 18 19 ## Count number of connecting nodes 20 21 Use `expand(_all_)` to expand the nodes' edges, then assign them to a variable. 22 The variable can now be used to iterate over the unique neighboring nodes. 23 Then use `count(uid)` to count the number of nodes in a block. 24 25 {{< runnable >}} 26 { 27 uids(func: has(director.film), first: 1) { 28 uid 29 expand(_all_) { u as uid } 30 } 31 32 result(func: uid(u)) { 33 count(uid) 34 } 35 } 36 {{< /runnable >}} 37 38 ## Search on non-indexed predicates 39 40 Use the `has` function among the value variables to search on non-indexed predicates. 41 42 {{< runnable >}} 43 { 44 var(func: has(festival.date_founded)) { 45 p as festival.date_founded 46 } 47 query(func: eq(val(p), "1961-01-01T00:00:00Z")) { 48 uid 49 name@en 50 name@ru 51 name@pl 52 festival.date_founded 53 festival.focus { name@en } 54 festival.individual_festivals { total : count(uid) } 55 } 56 } 57 {{< /runnable >}} 58 59 ## Sort edge by nested node values 60 61 Dgraph [sorting]({{< relref "query-language/index.md#sorting" >}}) is based on a single 62 level of the subgraph. To sort a level by the values of a deeper level, use 63 [query variables]({{< relref "query-language/index.md#query-variables" >}}) to bring 64 nested values up to the level of the edge to be sorted. 65 66 Example: Get all actors from a Steven Spielberg movie sorted alphabetically. 67 The actor's name is not accessed from a single traversal from the `starring` edge; 68 the name is accessible via `performance.actor`. 69 70 {{< runnable >}} 71 { 72 spielbergMovies as var(func: allofterms(name@en, "steven spielberg")) { 73 name@en 74 director.film (orderasc: name@en, first: 1) { 75 starring { 76 performance.actor { 77 ActorName as name@en 78 } 79 # Stars is a uid-to-value map mapping 80 # starring edges to performance.actor names 81 Stars as min(val(ActorName)) 82 } 83 } 84 } 85 86 movies(func: uid(spielbergMovies)) @cascade { 87 name@en 88 director.film (orderasc: name@en, first: 1) { 89 name@en 90 starring (orderasc: val(Stars)) { 91 performance.actor { 92 name@en 93 } 94 } 95 } 96 } 97 } 98 {{< /runnable >}} 99 100 ## Obtain unique results by using variables 101 102 To obtain unique results, assign the node's edge to a variable. 103 The variable can now be used to iterate over the unique nodes. 104 105 Example: Get all unique genres from all of the movies directed by Steven Spielberg. 106 107 {{< runnable >}} 108 { 109 var(func: eq(name@en, "Steven Spielberg")) { 110 director.film { 111 genres as genre 112 } 113 } 114 115 q(func: uid(genres)) { 116 name@. 117 } 118 } 119 {{< /runnable >}}