Ask a Question

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.

{
  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)
  }
}
curl -H "Content-Type: application/dql" localhost:8080/query -XPOST -d '
blahblah' | python -m json.tool | less
package main

import (
	"context"
	"flag"
	"fmt"
	"log"
    
	"github.com/dgraph-io/dgo/v2"
	"github.com/dgraph-io/dgo/v2/protos/api"
    
	"google.golang.org/grpc"
)

var (
	dgraph = flag.String("d", "127.0.0.1:9080", "Dgraph Alpha address")
)

func main() {
	flag.Parse()
	conn, err := grpc.Dial(*dgraph, grpc.WithInsecure())
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close()

	dg := dgo.NewDgraphClient(api.NewDgraphClient(conn))
    
	resp, err := dg.NewTxn().Query(context.Background(), `blahblah`)
	
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Response: %s\n", resp.Json)
}
import io.dgraph.DgraphClient;
import io.dgraph.DgraphGrpc;
import io.dgraph.DgraphGrpc.DgraphStub;
import io.dgraph.DgraphProto.Response;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;

import java.util.Map;

public class App {

    public static void main(final String[] args) {
        ManagedChannel channel =
            ManagedChannelBuilder.forAddress("localhost", 9080).usePlaintext(true).build();
        DgraphStub stub = DgraphGrpc.newStub(channel);
        DgraphClient dgraphClient = new DgraphClient(stub);

        String query = "blahblah";

    
        Response res = dgraphClient.newTransaction().query(query);
    
        System.out.printf("Response: %s", res.getJson().toStringUtf8());
    }
}

import pydgraph
import json

def main():
    client_stub = pydgraph.DgraphClientStub("localhost:9080")
    client = pydgraph.DgraphClient(client_stub)
    query = """blahblah"""
    res = client.txn(read_only=True).query(query)
    print('Response: {}'.format(json.loads(res.json)))

    client_stub.close()


if __name__ == '__main__':
    try:
        main()
    except Exception as e:
        print('Error: {}'.format(e))

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 = `blahblah`;
  const response = await dgraphClient.newTxn().query(query);
  console.log("Response: ", JSON.stringify(response.getJson()));

  clientStub.close();
}

main().then().catch((e) => {
  console.log("ERROR: ", e);
});
const dgraph = require("dgraph-js-http");

async function main() {
  const clientStub = new dgraph.DgraphClientStub("http://localhost:8080");
  const dgraphClient = new dgraph.DgraphClient(clientStub);

  const query = `blahblah`;
  const response = await dgraphClient.newTxn().query(query);
  console.log("Response: ", JSON.stringify(response.data));
}

main().then().catch((e) => {
  console.log("ERROR: ", e);
});
Response

Query Example: Actors from Tim Burton movies and how many roles they have played in Tim Burton movies.

{
  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)
  }
}
curl -H "Content-Type: application/dql" localhost:8080/query -XPOST -d '
blahblah' | python -m json.tool | less
package main

import (
	"context"
	"flag"
	"fmt"
	"log"
    
	"github.com/dgraph-io/dgo/v2"
	"github.com/dgraph-io/dgo/v2/protos/api"
    
	"google.golang.org/grpc"
)

var (
	dgraph = flag.String("d", "127.0.0.1:9080", "Dgraph Alpha address")
)

func main() {
	flag.Parse()
	conn, err := grpc.Dial(*dgraph, grpc.WithInsecure())
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close()

	dg := dgo.NewDgraphClient(api.NewDgraphClient(conn))
    
	resp, err := dg.NewTxn().Query(context.Background(), `blahblah`)
	
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Response: %s\n", resp.Json)
}
import io.dgraph.DgraphClient;
import io.dgraph.DgraphGrpc;
import io.dgraph.DgraphGrpc.DgraphStub;
import io.dgraph.DgraphProto.Response;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;

import java.util.Map;

public class App {

    public static void main(final String[] args) {
        ManagedChannel channel =
            ManagedChannelBuilder.forAddress("localhost", 9080).usePlaintext(true).build();
        DgraphStub stub = DgraphGrpc.newStub(channel);
        DgraphClient dgraphClient = new DgraphClient(stub);

        String query = "blahblah";

    
        Response res = dgraphClient.newTransaction().query(query);
    
        System.out.printf("Response: %s", res.getJson().toStringUtf8());
    }
}

import pydgraph
import json

def main():
    client_stub = pydgraph.DgraphClientStub("localhost:9080")
    client = pydgraph.DgraphClient(client_stub)
    query = """blahblah"""
    res = client.txn(read_only=True).query(query)
    print('Response: {}'.format(json.loads(res.json)))

    client_stub.close()


if __name__ == '__main__':
    try:
        main()
    except Exception as e:
        print('Error: {}'.format(e))

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 = `blahblah`;
  const response = await dgraphClient.newTxn().query(query);
  console.log("Response: ", JSON.stringify(response.getJson()));

  clientStub.close();
}

main().then().catch((e) => {
  console.log("ERROR: ", e);
});
const dgraph = require("dgraph-js-http");

async function main() {
  const clientStub = new dgraph.DgraphClientStub("http://localhost:8080");
  const dgraphClient = new dgraph.DgraphClient(clientStub);

  const query = `blahblah`;
  const response = await dgraphClient.newTxn().query(query);
  console.log("Response: ", JSON.stringify(response.data));
}

main().then().catch((e) => {
  console.log("ERROR: ", e);
});
Response