@groupby
Syntax Examples:
q(func: ...) @groupby(predicate) { min(...) }predicate @groupby(pred) { count(uid) }
A groupby query aggregates query results given a set of properties on which to group elements. For example, a query containing the block friend @groupby(age) { count(uid) }, finds all nodes reachable along the friend edge, partitions these into groups based on age, then counts how many nodes are in each group. The returned result is the grouped edges and the aggregations.
Inside a groupby block, only aggregations are allowed and count may only be applied to uid.
If the groupby is applied to a uid predicate, the resulting aggregations can be saved in a variable (mapping the grouped UIDs to aggregate values) and used elsewhere in the query to extract information other than the grouped or aggregated edges.
Query Example: For Steven Spielberg movies, count the number of movies in each genre and for each of those genres return the genre name and the count. The name can't be extracted in the groupby because it is not an aggregate, but uid(a) can be used to extract the UIDs from the UID to value map and thus organize the byGenre query by genre UID.
- Query
- Go
- Java
- Python
- JavaScript (gRPC)
- JavaScript (HTTP)
- Curl
{
var(func:allofterms(name@en, "steven spielberg")) {
director.film @groupby(genre) {
a as count(uid)
# a is a genre UID to count value variable
}
}
byGenre(func: uid(a), orderdesc: val(a)) {
name@en
total_movies : 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:allofterms(name@en, "steven spielberg")) {
director.film @groupby(genre) {
a as count(uid)
# a is a genre UID to count value variable
}
}
byGenre(func: uid(a), orderdesc: val(a)) {
name@en
total_movies : 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:allofterms(name@en, \"steven spielberg\")) {
director.film @groupby(genre) {
a as count(uid)
# a is a genre UID to count value variable
}
}
byGenre(func: uid(a), orderdesc: val(a)) {
name@en
total_movies : 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:allofterms(name@en, "steven spielberg")) {
director.film @groupby(genre) {
a as count(uid)
# a is a genre UID to count value variable
}
}
byGenre(func: uid(a), orderdesc: val(a)) {
name@en
total_movies : 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:allofterms(name@en, "steven spielberg")) {
director.film @groupby(genre) {
a as count(uid)
# a is a genre UID to count value variable
}
}
byGenre(func: uid(a), orderdesc: val(a)) {
name@en
total_movies : 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:allofterms(name@en, "steven spielberg")) {
director.film @groupby(genre) {
a as count(uid)
# a is a genre UID to count value variable
}
}
byGenre(func: uid(a), orderdesc: val(a)) {
name@en
total_movies : 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:allofterms(name@en, "steven spielberg")) {
director.film @groupby(genre) {
a as count(uid)
# a is a genre UID to count value variable
}
}
byGenre(func: uid(a), orderdesc: val(a)) {
name@en
total_movies : val(a)
}
}'
Query Example: Actors from Tim Burton movies and how many roles they have played in Tim Burton movies.
- Query
- Go
- Java
- Python
- JavaScript (gRPC)
- JavaScript (HTTP)
- Curl
{
var(func:allofterms(name@en, "Tim Burton")) {
director.film {
starring @groupby(performance.actor) {
a as count(uid)
# a is an actor UID to count value variable
}
}
}
byActor(func: uid(a), orderdesc: val(a)) {
name@en
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:allofterms(name@en, "Tim Burton")) {
director.film {
starring @groupby(performance.actor) {
a as count(uid)
# a is an actor UID to count value variable
}
}
}
byActor(func: uid(a), orderdesc: val(a)) {
name@en
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:allofterms(name@en, \"Tim Burton\")) {
director.film {
starring @groupby(performance.actor) {
a as count(uid)
# a is an actor UID to count value variable
}
}
}
byActor(func: uid(a), orderdesc: val(a)) {
name@en
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:allofterms(name@en, "Tim Burton")) {
director.film {
starring @groupby(performance.actor) {
a as count(uid)
# a is an actor UID to count value variable
}
}
}
byActor(func: uid(a), orderdesc: val(a)) {
name@en
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:allofterms(name@en, "Tim Burton")) {
director.film {
starring @groupby(performance.actor) {
a as count(uid)
# a is an actor UID to count value variable
}
}
}
byActor(func: uid(a), orderdesc: val(a)) {
name@en
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:allofterms(name@en, "Tim Burton")) {
director.film {
starring @groupby(performance.actor) {
a as count(uid)
# a is an actor UID to count value variable
}
}
}
byActor(func: uid(a), orderdesc: val(a)) {
name@en
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:allofterms(name@en, "Tim Burton")) {
director.film {
starring @groupby(performance.actor) {
a as count(uid)
# a is an actor UID to count value variable
}
}
}
byActor(func: uid(a), orderdesc: val(a)) {
name@en
val(a)
}
}'