Count Queries in GraphQL

Possible Alternative for countData type queries

The method to have separate queries of the type countData has the following drawbacks:

  1. The query has only one field in their return type which is count of UIDs matching filter. It cannot have any other fields of the Data type.
  2. For most purposes, a countData query will have to be accompanied by queryData query. As countData query does not return anything more than count of UIDs. It may not prove that useful as it is intended to be.

To solve this problem of countData type query, the alternative is to make all queryData type queries return an extra field count . This field will contain the count of UIDs satisfying the given filter condition.

This approach has the following advantages:

  1. Any other fields of Data type could also be queried along with this count variable. Making it easier to get all needed data using a single queryData query rather than using 2 queries, countData and queryData.
  2. This way of having a count variable in queryData is more consistent with the way count is handled in DQL. There is no separate countData query in DQL. Rather, a count(UID) variable is present which could be used to get a count of matching UIDs. This will make rewriting to DQL easier.

This approach has the following disadvantage:

  1. This will be a breaking change as the return type of queries of the form, queryData will change from [Data] to a structure containing int (to store count) and Data. This will have to be implemented and tested with greater care to avoid any problems with current structure.

Sample Example:

type Data {
	id: ID!
    name: String!
	intList: [Int]
	stringList: [String]
 	metaData: [Data]
}

The following queryData query will be generated in output schema from the above input schema.

query {
    queryData(filter: DataFilter): (Int, [Data])
}

Example GraphQL count query:

query {
    queryData(filter: \*Some Filter*\) {
        count
        name
        stringList
    }
}

The above GraphQL query would be rewritten to the following DQL query.

query {
    queryData(func: type(Data)) @filter(/* rewritten filter condtition */)) {
        count: count(uid)
        name
        stringList
    }
}

@amaster507, I will like to hear your comments about this and whether this solves some of the concerns mentioned by you.

1 Like