How to count the number of results with AWS Amplify DynamoDB and GraphQL

2019-12-10

How to get the total count of results with DynamoDB and GraphQL in order to paginate my results?

Many engineers using AWS Amplify are facing the same issue.

If you are about to bang your head against the wall, stop.

I’ll show you how to do it.

From the DynamoDB documentation:

the Query response contains the following elements:

ScannedCount — The number of items that matched the key condition expression before a filter expression (if present) was applied.

Count — The number of items that remain after a filter expression (if present) was applied.

The problem is that the automatically generated queries from Amplify don’t have those fields.

This is an example of a query that lists users:

export const listUsers = /* GraphQL */ `
  query ListUsers(
    $filter: ModelAlertFilterInput
    $limit: Int
    $nextToken: String
  ) {
    listUsers(filter: $filter, limit: $limit, nextToken: $nextToken) {
      items {
        id
        status
        groupCanAccess
        owner
        ...
      }
      nextToken
    }
  }
`;

And so, there will be no scannedCount and count in the result.

To make them magically appear, open your amplify/backend/api/deepboard/build/schema.graphql

and look for the definition of the type Query.

You’ll find somthing like this

type Query {
  getUser(id: ID!): User
  listUsers(filter: ModelUserFilterInput, limit: Int, nextToken: String): ModelUserConnection
  ...
}

a listUsers field that returns a type of ModelUserConnection, that is the result type that we want to edit.

Copy the type ModelUserConnection in your amplify/backend/api/<project-name>/schema.graphql to override it.


type ModelUserConnection {
  items: [User]
  nextToken: String
}

Add the scannedCount and count fields.


type ModelUserConnection {
  items: [User]
  nextToken: String
  scannedCount: Int
  count: Int
}

Now type amplify push and enjoy.

Now the query will return the scannedCount and count and you can happily paginate your results.

Remember that if the size of the Query result set is larger than 1 MB, scannedCount and count represent only a partial count of the total items. You need to perform multiple Query operations to retrieve all the results.

Keep Learning
Until next time