Dgraph GraphQL Tour

Basic

Count

You may have noticed that Dgraph generates an <edgeName>Aggregate edge for every edge pointing to a list. These aggregate edges, along with aggregate queries, allow you to count the number of items in a query without the need to return every node.

These aggregate operations return an aggregate result type generated as <type>AggregateResult. This type provides a unique set of fields for counting and finding the minimum, maximum, average, and sum values depending on the types in the schema.

The example query provided here requests every available field from PersonAggregateResult to return aggregate results from Alice’s friends, as follows:

  • count - count how many friends Alice has
  • xidMin - find the minimum xid value sorted alphabetically
  • xidMax - find the maximum xid value sorted alphabetically
  • nameMin - find the minimum name value sorted alphabetically
  • nameMax - find the maximum name value sorted alphabetically
  • ageMin - find the minimum age of Alice’s friends
  • ageMax - find the maximum age of Alice’s friends
  • ageAvg - find the average age of Alice’s friends
  • ageSum - sum of all of the ages of Alice’s friends
Note

The <field>Avg field only averages the values by the nodes that have a value set. If you have not altered the data from the Introduction, Alice has six friends, but only four of them have an age set. The sum age is 113 and the average age across those four nodes is 28.25.

To introspect into the schema for the available fields on the aggregate edges and queries, try the following:

{
  __type(name: "<type>AggregateResult") {
    name
    fields {
      name
    }
  }
}

2.9 Count