Aggregation
Syntax Example: AG(val(varName))
For AG replaced with
min: select the minimum value in the value variablevarNamemax: select the maximum valuesum: sum all values in value variablevarNameavg: calculate the average of values invarName
Schema Types:
| Aggregation | Schema Types |
|---|---|
min / max | int, float, string, dateTime, default |
sum / avg | int, float |
Aggregation can only be applied to value variables. An index is not required (the values have already been found and stored in the value variable mapping).
An aggregation is applied at the query block enclosing the variable definition. As opposed to query variables and value variables, which are global, aggregation is computed locally. For example:
A as predicateA {
...
B as predicateB {
x as ...some value...
}
min(val(x))
}
Here, A and B are the lists of all UIDs that match these blocks. Value variable x is a mapping from UIDs in B to values. The aggregation min(val(x)), however, is computed for each UID in A. That is, it has a semantics of: for each UID in A, take the slice of x that corresponds to A's outgoing predicateB edges and compute the aggregation for those values.
Aggregations can themselves be assigned to value variables, making a UID to aggregation map.
Min
Usage at Root
Query Example: Get the min initial release date for any Harry Potter movie.
The release date is assigned to a variable, then it is aggregated and fetched in an empty block.
- Query
- Go
- Java
- Python
- JavaScript (gRPC)
- JavaScript (HTTP)
- Curl
{
var(func: allofterms(name@en, "Harry Potter")) {
d as initial_release_date
}
me() {
min(val(d))
}
}
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"google.golang.org/grpc"
"github.com/dgraph-io/dgo/v230"
"github.com/dgraph-io/dgo/v230/protos/api"
)
func main() {
conn, err := grpc.Dial("localhost:9080", grpc.WithInsecure())
if err != nil {
log.Fatal(err)
}
defer conn.Close()
dgraphClient := dgo.NewDgraphClient(api.NewDgraphClient(conn))
ctx := context.Background()
txn := dgraphClient.NewTxn()
defer txn.Discard(ctx)
query := `{
var(func: allofterms(name@en, "Harry Potter")) {
d as initial_release_date
}
me() {
min(val(d))
}
}`
resp, err := txn.Query(ctx, query)
if err != nil {
log.Fatal(err)
}
var result map[string]interface{}
json.Unmarshal(resp.Json, &result)
fmt.Printf("%+v\n", result)
}
import io.dgraph.DgraphClient;
import io.dgraph.DgraphGrpc;
import io.dgraph.DgraphProto;
import io.dgraph.Transaction;
import java.util.Map;
public class App {
public static void main(String[] args) {
ManagedChannel channel = ManagedChannelBuilder
.forAddress("localhost", 9080)
.usePlaintext()
.build();
DgraphGrpc.DgraphStub stub = DgraphGrpc.newStub(channel);
DgraphClient dgraphClient = new DgraphClient(stub);
String query = "{
var(func: allofterms(name@en, \"Harry Potter\")) {
d as initial_release_date
}
me() {
min(val(d))
}
}";
Transaction txn = dgraphClient.newTransaction();
try {
DgraphProto.Response response = txn.query(query);
System.out.println(response.getJson().toStringUtf8());
} finally {
txn.discard();
}
}
}
import grpc
from dgraph import DgraphClient, Txn
def main():
client_stub = DgraphClient("localhost:9080")
client = DgraphClient(client_stub)
query = """{
var(func: allofterms(name@en, "Harry Potter")) {
d as initial_release_date
}
me() {
min(val(d))
}
}"""
txn = client.txn()
try:
response = txn.query(query)
print(response.json)
finally:
txn.discard()
if __name__ == "__main__":
main()
const dgraph = require("dgraph-js");
const grpc = require("grpc");
async function main() {
const clientStub = new dgraph.DgraphClientStub(
"localhost:9080",
grpc.credentials.createInsecure()
);
const dgraphClient = new dgraph.DgraphClient(clientStub);
const query = `{
var(func: allofterms(name@en, "Harry Potter")) {
d as initial_release_date
}
me() {
min(val(d))
}
}`;
const txn = dgraphClient.newTxn();
try {
const res = await txn.query(query);
const json = res.getJson();
console.log(JSON.stringify(JSON.parse(json), null, 2));
} finally {
await txn.discard();
}
}
main().catch((e) => {
console.error(e);
});
const fetch = require("node-fetch");
async function main() {
const query = `{
var(func: allofterms(name@en, "Harry Potter")) {
d as initial_release_date
}
me() {
min(val(d))
}
}`;
const response = await fetch("http://localhost:8080/query", {
method: "POST",
headers: {
"Content-Type": "application/dql"
},
body: query
});
const result = await response.json();
console.log(JSON.stringify(result, null, 2));
}
main().catch((e) => {
console.error(e);
});
curl -X POST http://localhost:8080/query \
-H "Content-Type: application/dql" \
-d '{
var(func: allofterms(name@en, "Harry Potter")) {
d as initial_release_date
}
me() {
min(val(d))
}
}'
Usage at other levels
Query Example: Directors called Steven and the date of release of their first movie, in ascending order of first movie.
- Query
- Go
- Java
- Python
- JavaScript (gRPC)
- JavaScript (HTTP)
- Curl
{
stevens as var(func: allofterms(name@en, "steven")) {
director.film {
ird as initial_release_date
# ird is a value variable mapping a film UID to its release date
}
minIRD as min(val(ird))
# minIRD is a value variable mapping a director UID to their first release date
}
byIRD(func: uid(stevens), orderasc: val(minIRD)) {
name@en
firstRelease: val(minIRD)
}
}
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"google.golang.org/grpc"
"github.com/dgraph-io/dgo/v230"
"github.com/dgraph-io/dgo/v230/protos/api"
)
func main() {
conn, err := grpc.Dial("localhost:9080", grpc.WithInsecure())
if err != nil {
log.Fatal(err)
}
defer conn.Close()
dgraphClient := dgo.NewDgraphClient(api.NewDgraphClient(conn))
ctx := context.Background()
txn := dgraphClient.NewTxn()
defer txn.Discard(ctx)
query := `{
stevens as var(func: allofterms(name@en, "steven")) {
director.film {
ird as initial_release_date
# ird is a value variable mapping a film UID to its release date
}
minIRD as min(val(ird))
# minIRD is a value variable mapping a director UID to their first release date
}
byIRD(func: uid(stevens), orderasc: val(minIRD)) {
name@en
firstRelease: val(minIRD)
}
}`
resp, err := txn.Query(ctx, query)
if err != nil {
log.Fatal(err)
}
var result map[string]interface{}
json.Unmarshal(resp.Json, &result)
fmt.Printf("%+v\n", result)
}
import io.dgraph.DgraphClient;
import io.dgraph.DgraphGrpc;
import io.dgraph.DgraphProto;
import io.dgraph.Transaction;
import java.util.Map;
public class App {
public static void main(String[] args) {
ManagedChannel channel = ManagedChannelBuilder
.forAddress("localhost", 9080)
.usePlaintext()
.build();
DgraphGrpc.DgraphStub stub = DgraphGrpc.newStub(channel);
DgraphClient dgraphClient = new DgraphClient(stub);
String query = "{
stevens as var(func: allofterms(name@en, \"steven\")) {
director.film {
ird as initial_release_date
# ird is a value variable mapping a film UID to its release date
}
minIRD as min(val(ird))
# minIRD is a value variable mapping a director UID to their first release date
}
byIRD(func: uid(stevens), orderasc: val(minIRD)) {
name@en
firstRelease: val(minIRD)
}
}";
Transaction txn = dgraphClient.newTransaction();
try {
DgraphProto.Response response = txn.query(query);
System.out.println(response.getJson().toStringUtf8());
} finally {
txn.discard();
}
}
}
import grpc
from dgraph import DgraphClient, Txn
def main():
client_stub = DgraphClient("localhost:9080")
client = DgraphClient(client_stub)
query = """{
stevens as var(func: allofterms(name@en, "steven")) {
director.film {
ird as initial_release_date
# ird is a value variable mapping a film UID to its release date
}
minIRD as min(val(ird))
# minIRD is a value variable mapping a director UID to their first release date
}
byIRD(func: uid(stevens), orderasc: val(minIRD)) {
name@en
firstRelease: val(minIRD)
}
}"""
txn = client.txn()
try:
response = txn.query(query)
print(response.json)
finally:
txn.discard()
if __name__ == "__main__":
main()
const dgraph = require("dgraph-js");
const grpc = require("grpc");
async function main() {
const clientStub = new dgraph.DgraphClientStub(
"localhost:9080",
grpc.credentials.createInsecure()
);
const dgraphClient = new dgraph.DgraphClient(clientStub);
const query = `{
stevens as var(func: allofterms(name@en, "steven")) {
director.film {
ird as initial_release_date
# ird is a value variable mapping a film UID to its release date
}
minIRD as min(val(ird))
# minIRD is a value variable mapping a director UID to their first release date
}
byIRD(func: uid(stevens), orderasc: val(minIRD)) {
name@en
firstRelease: val(minIRD)
}
}`;
const txn = dgraphClient.newTxn();
try {
const res = await txn.query(query);
const json = res.getJson();
console.log(JSON.stringify(JSON.parse(json), null, 2));
} finally {
await txn.discard();
}
}
main().catch((e) => {
console.error(e);
});
const fetch = require("node-fetch");
async function main() {
const query = `{
stevens as var(func: allofterms(name@en, "steven")) {
director.film {
ird as initial_release_date
# ird is a value variable mapping a film UID to its release date
}
minIRD as min(val(ird))
# minIRD is a value variable mapping a director UID to their first release date
}
byIRD(func: uid(stevens), orderasc: val(minIRD)) {
name@en
firstRelease: val(minIRD)
}
}`;
const response = await fetch("http://localhost:8080/query", {
method: "POST",
headers: {
"Content-Type": "application/dql"
},
body: query
});
const result = await response.json();
console.log(JSON.stringify(result, null, 2));
}
main().catch((e) => {
console.error(e);
});
curl -X POST http://localhost:8080/query \
-H "Content-Type: application/dql" \
-d '{
stevens as var(func: allofterms(name@en, "steven")) {
director.film {
ird as initial_release_date
# ird is a value variable mapping a film UID to its release date
}
minIRD as min(val(ird))
# minIRD is a value variable mapping a director UID to their first release date
}
byIRD(func: uid(stevens), orderasc: val(minIRD)) {
name@en
firstRelease: val(minIRD)
}
}'
Max
Usage at Root
Query Example: Get the max initial release date for any Harry Potter movie.
The release date is assigned to a variable, then it is aggregated and fetched in an empty block.
- Query
- Go
- Java
- Python
- JavaScript (gRPC)
- JavaScript (HTTP)
- Curl
{
var(func: allofterms(name@en, "Harry Potter")) {
d as initial_release_date
}
me() {
max(val(d))
}
}
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"google.golang.org/grpc"
"github.com/dgraph-io/dgo/v230"
"github.com/dgraph-io/dgo/v230/protos/api"
)
func main() {
conn, err := grpc.Dial("localhost:9080", grpc.WithInsecure())
if err != nil {
log.Fatal(err)
}
defer conn.Close()
dgraphClient := dgo.NewDgraphClient(api.NewDgraphClient(conn))
ctx := context.Background()
txn := dgraphClient.NewTxn()
defer txn.Discard(ctx)
query := `{
var(func: allofterms(name@en, "Harry Potter")) {
d as initial_release_date
}
me() {
max(val(d))
}
}`
resp, err := txn.Query(ctx, query)
if err != nil {
log.Fatal(err)
}
var result map[string]interface{}
json.Unmarshal(resp.Json, &result)
fmt.Printf("%+v\n", result)
}
import io.dgraph.DgraphClient;
import io.dgraph.DgraphGrpc;
import io.dgraph.DgraphProto;
import io.dgraph.Transaction;
import java.util.Map;
public class App {
public static void main(String[] args) {
ManagedChannel channel = ManagedChannelBuilder
.forAddress("localhost", 9080)
.usePlaintext()
.build();
DgraphGrpc.DgraphStub stub = DgraphGrpc.newStub(channel);
DgraphClient dgraphClient = new DgraphClient(stub);
String query = "{
var(func: allofterms(name@en, \"Harry Potter\")) {
d as initial_release_date
}
me() {
max(val(d))
}
}";
Transaction txn = dgraphClient.newTransaction();
try {
DgraphProto.Response response = txn.query(query);
System.out.println(response.getJson().toStringUtf8());
} finally {
txn.discard();
}
}
}
import grpc
from dgraph import DgraphClient, Txn
def main():
client_stub = DgraphClient("localhost:9080")
client = DgraphClient(client_stub)
query = """{
var(func: allofterms(name@en, "Harry Potter")) {
d as initial_release_date
}
me() {
max(val(d))
}
}"""
txn = client.txn()
try:
response = txn.query(query)
print(response.json)
finally:
txn.discard()
if __name__ == "__main__":
main()
const dgraph = require("dgraph-js");
const grpc = require("grpc");
async function main() {
const clientStub = new dgraph.DgraphClientStub(
"localhost:9080",
grpc.credentials.createInsecure()
);
const dgraphClient = new dgraph.DgraphClient(clientStub);
const query = `{
var(func: allofterms(name@en, "Harry Potter")) {
d as initial_release_date
}
me() {
max(val(d))
}
}`;
const txn = dgraphClient.newTxn();
try {
const res = await txn.query(query);
const json = res.getJson();
console.log(JSON.stringify(JSON.parse(json), null, 2));
} finally {
await txn.discard();
}
}
main().catch((e) => {
console.error(e);
});
const fetch = require("node-fetch");
async function main() {
const query = `{
var(func: allofterms(name@en, "Harry Potter")) {
d as initial_release_date
}
me() {
max(val(d))
}
}`;
const response = await fetch("http://localhost:8080/query", {
method: "POST",
headers: {
"Content-Type": "application/dql"
},
body: query
});
const result = await response.json();
console.log(JSON.stringify(result, null, 2));
}
main().catch((e) => {
console.error(e);
});
curl -X POST http://localhost:8080/query \
-H "Content-Type: application/dql" \
-d '{
var(func: allofterms(name@en, "Harry Potter")) {
d as initial_release_date
}
me() {
max(val(d))
}
}'
Usage at other levels
Query Example: Quentin Tarantino's movies and date of release of the most recent movie.
- Query
- Go
- Java
- Python
- JavaScript (gRPC)
- JavaScript (HTTP)
- Curl
{
director(func: allofterms(name@en, "Quentin Tarantino")) {
director.film {
name@en
x as initial_release_date
}
max(val(x))
}
}
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"google.golang.org/grpc"
"github.com/dgraph-io/dgo/v230"
"github.com/dgraph-io/dgo/v230/protos/api"
)
func main() {
conn, err := grpc.Dial("localhost:9080", grpc.WithInsecure())
if err != nil {
log.Fatal(err)
}
defer conn.Close()
dgraphClient := dgo.NewDgraphClient(api.NewDgraphClient(conn))
ctx := context.Background()
txn := dgraphClient.NewTxn()
defer txn.Discard(ctx)
query := `{
director(func: allofterms(name@en, "Quentin Tarantino")) {
director.film {
name@en
x as initial_release_date
}
max(val(x))
}
}`
resp, err := txn.Query(ctx, query)
if err != nil {
log.Fatal(err)
}
var result map[string]interface{}
json.Unmarshal(resp.Json, &result)
fmt.Printf("%+v\n", result)
}
import io.dgraph.DgraphClient;
import io.dgraph.DgraphGrpc;
import io.dgraph.DgraphProto;
import io.dgraph.Transaction;
import java.util.Map;
public class App {
public static void main(String[] args) {
ManagedChannel channel = ManagedChannelBuilder
.forAddress("localhost", 9080)
.usePlaintext()
.build();
DgraphGrpc.DgraphStub stub = DgraphGrpc.newStub(channel);
DgraphClient dgraphClient = new DgraphClient(stub);
String query = "{
director(func: allofterms(name@en, \"Quentin Tarantino\")) {
director.film {
name@en
x as initial_release_date
}
max(val(x))
}
}";
Transaction txn = dgraphClient.newTransaction();
try {
DgraphProto.Response response = txn.query(query);
System.out.println(response.getJson().toStringUtf8());
} finally {
txn.discard();
}
}
}
import grpc
from dgraph import DgraphClient, Txn
def main():
client_stub = DgraphClient("localhost:9080")
client = DgraphClient(client_stub)
query = """{
director(func: allofterms(name@en, "Quentin Tarantino")) {
director.film {
name@en
x as initial_release_date
}
max(val(x))
}
}"""
txn = client.txn()
try:
response = txn.query(query)
print(response.json)
finally:
txn.discard()
if __name__ == "__main__":
main()
const dgraph = require("dgraph-js");
const grpc = require("grpc");
async function main() {
const clientStub = new dgraph.DgraphClientStub(
"localhost:9080",
grpc.credentials.createInsecure()
);
const dgraphClient = new dgraph.DgraphClient(clientStub);
const query = `{
director(func: allofterms(name@en, "Quentin Tarantino")) {
director.film {
name@en
x as initial_release_date
}
max(val(x))
}
}`;
const txn = dgraphClient.newTxn();
try {
const res = await txn.query(query);
const json = res.getJson();
console.log(JSON.stringify(JSON.parse(json), null, 2));
} finally {
await txn.discard();
}
}
main().catch((e) => {
console.error(e);
});
const fetch = require("node-fetch");
async function main() {
const query = `{
director(func: allofterms(name@en, "Quentin Tarantino")) {
director.film {
name@en
x as initial_release_date
}
max(val(x))
}
}`;
const response = await fetch("http://localhost:8080/query", {
method: "POST",
headers: {
"Content-Type": "application/dql"
},
body: query
});
const result = await response.json();
console.log(JSON.stringify(result, null, 2));
}
main().catch((e) => {
console.error(e);
});
curl -X POST http://localhost:8080/query \
-H "Content-Type: application/dql" \
-d '{
director(func: allofterms(name@en, "Quentin Tarantino")) {
director.film {
name@en
x as initial_release_date
}
max(val(x))
}
}'
Sum and Avg
Usage at Root
Query Example: Get the sum and average of number of count of movies directed by people who have Steven or Tom in their name.
- Query
- Go
- Java
- Python
- JavaScript (gRPC)
- JavaScript (HTTP)
- Curl
{
var(func: anyofterms(name@en, "Steven Tom")) {
a as count(director.film)
}
me() {
avg(val(a))
sum(val(a))
}
}
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"google.golang.org/grpc"
"github.com/dgraph-io/dgo/v230"
"github.com/dgraph-io/dgo/v230/protos/api"
)
func main() {
conn, err := grpc.Dial("localhost:9080", grpc.WithInsecure())
if err != nil {
log.Fatal(err)
}
defer conn.Close()
dgraphClient := dgo.NewDgraphClient(api.NewDgraphClient(conn))
ctx := context.Background()
txn := dgraphClient.NewTxn()
defer txn.Discard(ctx)
query := `{
var(func: anyofterms(name@en, "Steven Tom")) {
a as count(director.film)
}
me() {
avg(val(a))
sum(val(a))
}
}`
resp, err := txn.Query(ctx, query)
if err != nil {
log.Fatal(err)
}
var result map[string]interface{}
json.Unmarshal(resp.Json, &result)
fmt.Printf("%+v\n", result)
}
import io.dgraph.DgraphClient;
import io.dgraph.DgraphGrpc;
import io.dgraph.DgraphProto;
import io.dgraph.Transaction;
import java.util.Map;
public class App {
public static void main(String[] args) {
ManagedChannel channel = ManagedChannelBuilder
.forAddress("localhost", 9080)
.usePlaintext()
.build();
DgraphGrpc.DgraphStub stub = DgraphGrpc.newStub(channel);
DgraphClient dgraphClient = new DgraphClient(stub);
String query = "{
var(func: anyofterms(name@en, \"Steven Tom\")) {
a as count(director.film)
}
me() {
avg(val(a))
sum(val(a))
}
}";
Transaction txn = dgraphClient.newTransaction();
try {
DgraphProto.Response response = txn.query(query);
System.out.println(response.getJson().toStringUtf8());
} finally {
txn.discard();
}
}
}
import grpc
from dgraph import DgraphClient, Txn
def main():
client_stub = DgraphClient("localhost:9080")
client = DgraphClient(client_stub)
query = """{
var(func: anyofterms(name@en, "Steven Tom")) {
a as count(director.film)
}
me() {
avg(val(a))
sum(val(a))
}
}"""
txn = client.txn()
try:
response = txn.query(query)
print(response.json)
finally:
txn.discard()
if __name__ == "__main__":
main()
const dgraph = require("dgraph-js");
const grpc = require("grpc");
async function main() {
const clientStub = new dgraph.DgraphClientStub(
"localhost:9080",
grpc.credentials.createInsecure()
);
const dgraphClient = new dgraph.DgraphClient(clientStub);
const query = `{
var(func: anyofterms(name@en, "Steven Tom")) {
a as count(director.film)
}
me() {
avg(val(a))
sum(val(a))
}
}`;
const txn = dgraphClient.newTxn();
try {
const res = await txn.query(query);
const json = res.getJson();
console.log(JSON.stringify(JSON.parse(json), null, 2));
} finally {
await txn.discard();
}
}
main().catch((e) => {
console.error(e);
});
const fetch = require("node-fetch");
async function main() {
const query = `{
var(func: anyofterms(name@en, "Steven Tom")) {
a as count(director.film)
}
me() {
avg(val(a))
sum(val(a))
}
}`;
const response = await fetch("http://localhost:8080/query", {
method: "POST",
headers: {
"Content-Type": "application/dql"
},
body: query
});
const result = await response.json();
console.log(JSON.stringify(result, null, 2));
}
main().catch((e) => {
console.error(e);
});
curl -X POST http://localhost:8080/query \
-H "Content-Type: application/dql" \
-d '{
var(func: anyofterms(name@en, "Steven Tom")) {
a as count(director.film)
}
me() {
avg(val(a))
sum(val(a))
}
}'
Usage at other levels
Query Example: Steven Spielberg's movies, with the number of recorded genres per movie, and the total number of genres and average genres per movie.
- Query
- Go
- Java
- Python
- JavaScript (gRPC)
- JavaScript (HTTP)
- Curl
{
director(func: eq(name@en, "Steven Spielberg")) {
name@en
director.film {
name@en
numGenres : g as count(genre)
}
totalGenres : sum(val(g))
genresPerMovie : avg(val(g))
}
}
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"google.golang.org/grpc"
"github.com/dgraph-io/dgo/v230"
"github.com/dgraph-io/dgo/v230/protos/api"
)
func main() {
conn, err := grpc.Dial("localhost:9080", grpc.WithInsecure())
if err != nil {
log.Fatal(err)
}
defer conn.Close()
dgraphClient := dgo.NewDgraphClient(api.NewDgraphClient(conn))
ctx := context.Background()
txn := dgraphClient.NewTxn()
defer txn.Discard(ctx)
query := `{
director(func: eq(name@en, "Steven Spielberg")) {
name@en
director.film {
name@en
numGenres : g as count(genre)
}
totalGenres : sum(val(g))
genresPerMovie : avg(val(g))
}
}`
resp, err := txn.Query(ctx, query)
if err != nil {
log.Fatal(err)
}
var result map[string]interface{}
json.Unmarshal(resp.Json, &result)
fmt.Printf("%+v\n", result)
}
import io.dgraph.DgraphClient;
import io.dgraph.DgraphGrpc;
import io.dgraph.DgraphProto;
import io.dgraph.Transaction;
import java.util.Map;
public class App {
public static void main(String[] args) {
ManagedChannel channel = ManagedChannelBuilder
.forAddress("localhost", 9080)
.usePlaintext()
.build();
DgraphGrpc.DgraphStub stub = DgraphGrpc.newStub(channel);
DgraphClient dgraphClient = new DgraphClient(stub);
String query = "{
director(func: eq(name@en, \"Steven Spielberg\")) {
name@en
director.film {
name@en
numGenres : g as count(genre)
}
totalGenres : sum(val(g))
genresPerMovie : avg(val(g))
}
}";
Transaction txn = dgraphClient.newTransaction();
try {
DgraphProto.Response response = txn.query(query);
System.out.println(response.getJson().toStringUtf8());
} finally {
txn.discard();
}
}
}
import grpc
from dgraph import DgraphClient, Txn
def main():
client_stub = DgraphClient("localhost:9080")
client = DgraphClient(client_stub)
query = """{
director(func: eq(name@en, "Steven Spielberg")) {
name@en
director.film {
name@en
numGenres : g as count(genre)
}
totalGenres : sum(val(g))
genresPerMovie : avg(val(g))
}
}"""
txn = client.txn()
try:
response = txn.query(query)
print(response.json)
finally:
txn.discard()
if __name__ == "__main__":
main()
const dgraph = require("dgraph-js");
const grpc = require("grpc");
async function main() {
const clientStub = new dgraph.DgraphClientStub(
"localhost:9080",
grpc.credentials.createInsecure()
);
const dgraphClient = new dgraph.DgraphClient(clientStub);
const query = `{
director(func: eq(name@en, "Steven Spielberg")) {
name@en
director.film {
name@en
numGenres : g as count(genre)
}
totalGenres : sum(val(g))
genresPerMovie : avg(val(g))
}
}`;
const txn = dgraphClient.newTxn();
try {
const res = await txn.query(query);
const json = res.getJson();
console.log(JSON.stringify(JSON.parse(json), null, 2));
} finally {
await txn.discard();
}
}
main().catch((e) => {
console.error(e);
});
const fetch = require("node-fetch");
async function main() {
const query = `{
director(func: eq(name@en, "Steven Spielberg")) {
name@en
director.film {
name@en
numGenres : g as count(genre)
}
totalGenres : sum(val(g))
genresPerMovie : avg(val(g))
}
}`;
const response = await fetch("http://localhost:8080/query", {
method: "POST",
headers: {
"Content-Type": "application/dql"
},
body: query
});
const result = await response.json();
console.log(JSON.stringify(result, null, 2));
}
main().catch((e) => {
console.error(e);
});
curl -X POST http://localhost:8080/query \
-H "Content-Type: application/dql" \
-d '{
director(func: eq(name@en, "Steven Spielberg")) {
name@en
director.film {
name@en
numGenres : g as count(genre)
}
totalGenres : sum(val(g))
genresPerMovie : avg(val(g))
}
}'
Aggregating Aggregates
Aggregations can be assigned to value variables, and so these variables can in turn be aggregated.
Query Example: For each actor in a Peter Jackson film, find the number of roles played in any movie. Sum these to find the total number of roles ever played by all actors in the movie. Then sum the lot to find the total number of roles ever played by actors who have appeared in Peter Jackson movies. Note that this demonstrates how to aggregate aggregates; the answer in this case isn't quite precise though, because actors that have appeared in multiple Peter Jackson movies are counted more than once.
- Query
- Go
- Java
- Python
- JavaScript (gRPC)
- JavaScript (HTTP)
- Curl
{
PJ as var(func:allofterms(name@en, "Peter Jackson")) {
director.film {
starring { # starring an actor
performance.actor {
movies as count(actor.film)
# number of roles for this actor
}
perf_total as sum(val(movies))
}
movie_total as sum(val(perf_total))
# total roles for all actors in this movie
}
gt as sum(val(movie_total))
}
PJmovies(func: uid(PJ)) {
name@en
director.film (orderdesc: val(movie_total), first: 5) {
name@en
totalRoles : val(movie_total)
}
grandTotal : val(gt)
}
}
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"google.golang.org/grpc"
"github.com/dgraph-io/dgo/v230"
"github.com/dgraph-io/dgo/v230/protos/api"
)
func main() {
conn, err := grpc.Dial("localhost:9080", grpc.WithInsecure())
if err != nil {
log.Fatal(err)
}
defer conn.Close()
dgraphClient := dgo.NewDgraphClient(api.NewDgraphClient(conn))
ctx := context.Background()
txn := dgraphClient.NewTxn()
defer txn.Discard(ctx)
query := `{
PJ as var(func:allofterms(name@en, "Peter Jackson")) {
director.film {
starring { # starring an actor
performance.actor {
movies as count(actor.film)
# number of roles for this actor
}
perf_total as sum(val(movies))
}
movie_total as sum(val(perf_total))
# total roles for all actors in this movie
}
gt as sum(val(movie_total))
}
PJmovies(func: uid(PJ)) {
name@en
director.film (orderdesc: val(movie_total), first: 5) {
name@en
totalRoles : val(movie_total)
}
grandTotal : val(gt)
}
}`
resp, err := txn.Query(ctx, query)
if err != nil {
log.Fatal(err)
}
var result map[string]interface{}
json.Unmarshal(resp.Json, &result)
fmt.Printf("%+v\n", result)
}
import io.dgraph.DgraphClient;
import io.dgraph.DgraphGrpc;
import io.dgraph.DgraphProto;
import io.dgraph.Transaction;
import java.util.Map;
public class App {
public static void main(String[] args) {
ManagedChannel channel = ManagedChannelBuilder
.forAddress("localhost", 9080)
.usePlaintext()
.build();
DgraphGrpc.DgraphStub stub = DgraphGrpc.newStub(channel);
DgraphClient dgraphClient = new DgraphClient(stub);
String query = "{
PJ as var(func:allofterms(name@en, \"Peter Jackson\")) {
director.film {
starring { # starring an actor
performance.actor {
movies as count(actor.film)
# number of roles for this actor
}
perf_total as sum(val(movies))
}
movie_total as sum(val(perf_total))
# total roles for all actors in this movie
}
gt as sum(val(movie_total))
}
PJmovies(func: uid(PJ)) {
name@en
director.film (orderdesc: val(movie_total), first: 5) {
name@en
totalRoles : val(movie_total)
}
grandTotal : val(gt)
}
}";
Transaction txn = dgraphClient.newTransaction();
try {
DgraphProto.Response response = txn.query(query);
System.out.println(response.getJson().toStringUtf8());
} finally {
txn.discard();
}
}
}
import grpc
from dgraph import DgraphClient, Txn
def main():
client_stub = DgraphClient("localhost:9080")
client = DgraphClient(client_stub)
query = """{
PJ as var(func:allofterms(name@en, "Peter Jackson")) {
director.film {
starring { # starring an actor
performance.actor {
movies as count(actor.film)
# number of roles for this actor
}
perf_total as sum(val(movies))
}
movie_total as sum(val(perf_total))
# total roles for all actors in this movie
}
gt as sum(val(movie_total))
}
PJmovies(func: uid(PJ)) {
name@en
director.film (orderdesc: val(movie_total), first: 5) {
name@en
totalRoles : val(movie_total)
}
grandTotal : val(gt)
}
}"""
txn = client.txn()
try:
response = txn.query(query)
print(response.json)
finally:
txn.discard()
if __name__ == "__main__":
main()
const dgraph = require("dgraph-js");
const grpc = require("grpc");
async function main() {
const clientStub = new dgraph.DgraphClientStub(
"localhost:9080",
grpc.credentials.createInsecure()
);
const dgraphClient = new dgraph.DgraphClient(clientStub);
const query = `{
PJ as var(func:allofterms(name@en, "Peter Jackson")) {
director.film {
starring { # starring an actor
performance.actor {
movies as count(actor.film)
# number of roles for this actor
}
perf_total as sum(val(movies))
}
movie_total as sum(val(perf_total))
# total roles for all actors in this movie
}
gt as sum(val(movie_total))
}
PJmovies(func: uid(PJ)) {
name@en
director.film (orderdesc: val(movie_total), first: 5) {
name@en
totalRoles : val(movie_total)
}
grandTotal : val(gt)
}
}`;
const txn = dgraphClient.newTxn();
try {
const res = await txn.query(query);
const json = res.getJson();
console.log(JSON.stringify(JSON.parse(json), null, 2));
} finally {
await txn.discard();
}
}
main().catch((e) => {
console.error(e);
});
const fetch = require("node-fetch");
async function main() {
const query = `{
PJ as var(func:allofterms(name@en, "Peter Jackson")) {
director.film {
starring { # starring an actor
performance.actor {
movies as count(actor.film)
# number of roles for this actor
}
perf_total as sum(val(movies))
}
movie_total as sum(val(perf_total))
# total roles for all actors in this movie
}
gt as sum(val(movie_total))
}
PJmovies(func: uid(PJ)) {
name@en
director.film (orderdesc: val(movie_total), first: 5) {
name@en
totalRoles : val(movie_total)
}
grandTotal : val(gt)
}
}`;
const response = await fetch("http://localhost:8080/query", {
method: "POST",
headers: {
"Content-Type": "application/dql"
},
body: query
});
const result = await response.json();
console.log(JSON.stringify(result, null, 2));
}
main().catch((e) => {
console.error(e);
});
curl -X POST http://localhost:8080/query \
-H "Content-Type: application/dql" \
-d '{
PJ as var(func:allofterms(name@en, "Peter Jackson")) {
director.film {
starring { # starring an actor
performance.actor {
movies as count(actor.film)
# number of roles for this actor
}
perf_total as sum(val(movies))
}
movie_total as sum(val(perf_total))
# total roles for all actors in this movie
}
gt as sum(val(movie_total))
}
PJmovies(func: uid(PJ)) {
name@en
director.film (orderdesc: val(movie_total), first: 5) {
name@en
totalRoles : val(movie_total)
}
grandTotal : val(gt)
}
}'