Count Queries in GraphQL

Extending Count to Aggregate queries

As mentioned in the above posts that the aggregateData query would later on be extended to other aggregate functions like avg, min, max, sum , here are some examples of GraphQL to DQL queries on how that will work.

sum, avg functions would be allowed on field which are of the type Int or Float . sum would have the same return type as the value on which it operates. avg would always be of the type Float to cater to cases in which the sum of values is not divisible by number of predicates.

min , max functions would operate on fields which are of the type Int , Float, String, Datetime and would have the same return type as the field on which it operates.

Aggregate queries at Root level

For the following GraphQL schema

type Data {
  name: String!
  metaData: [Metadata]
}

The following DataAggregateResult input type will be generated

input DataAggregateResult {
  count: Int
  min_name: String
  max_name: String
}

The following GraphQL query

query {
    aggregateData(filter: DataFilter) {
        min_name
    }
}

would translate to the following DQL query

{
  var(func: type(Data)) @filter(/* rewritten filter condition */) {
    a as name
  }

  me() {
    min(val(a))
  }
}

Note that as aggregate functions and count are treated differently in DQL queries. GraphQL queries with both count and aggregate functions would be rewritten to multiple DQL queries and combined together before returning.

Aggregate queries at other levels

query {
    queryData {
        name
        metaData_aggregate {
            min_metadata_field  // metadata_field is some field in type metadata of type string
        }
    }
}

The above GraphQL query would translate to the following DQL query

{
  data as var(func: type(Data))  {
    metaData {
        field as metadata_field
    }
    minField as min(val(field))
  }

  me(func: uid(data)) {
    name
    val(minField)
  }
}

A Note about count queries

It was mentioned in the first post that scalar fields like intList: [Int] would also support count operations. But, with the new model, it won’t be possible to support this as the AggregateData input field would only have a single count variable and all other count functions of fields like metaData will take place at a different level (inside metaData_aggregate field).

As counting of such scalar arrays is supported in DQL, one would still be able to get count of scalar arrays using custom DQL.

1 Like