Best way to count items on AWS Amplify with GraphQL

2.3k Views Asked by At

Stack: React on AWS Amplify with GraphQL(DynamoDB)

Since non-relationship database does not offer SELECT .. COUNT .. FROM ..., it has been an issue for me to effectively show the number of items on my app.

Current implementation is to update count manually. Every time new post is created by a user, I manually update post count + 1 with separate call which will be saved under different DynamoDB table. This has an issue that the count + 1 request does not always execute base on the internet connection status.

Another option is to use scan operator on DynamoDB that is not efficient at all since it needs to go through all items in the table that can have over millions of rows.

Seems like @searchable directive can be an option that can be called as a query when new post is created, execute query to search all post by user ID and get the total count number. However, I'm not very familiar with this solution and not sure how the performance will be plus running cost(since it requires EC2)

How did you solve this issue and what is the best way to implement this?

2

There are 2 best solutions below

0
AudioBubble On

AmplifyCountDirective

AmplifyCountDirective provides the ability to count the number of items in your DynamoDB tables using Amplify.

Example This package provides the @count directive which can be used to annotate your models. Let's say we use it in the following schema:

type Foo @count @model {
  id: ID!
  string_field: String
  int_field: Int
  float_field: Float
  bool_field: Boolean
}

This will compile into:

type Query {
    getFoo(id: ID!): Foo
    listFoos(filter: ModelFooFilterInput, limit: Int, nextToken: String): ModelFooConnection
    countFoo(filter: ModelFooFilterInput): Int
}

Finally you can query the number of items in your table using the same filters as you would use to list them:

{
  countFoo(filter: {
      and: {
          bool_field: {eq: false},
          float_field: {le: 1.5},
          string_field: {contains: "bar"}
      }
  })
}
0
vaquar khan On
  1. There is no efficient way for DynamoDB to count items, and it cannot generally perform aggregate operations. If you want to count items, write a custom lambda to read from the dynamo table stream and conditionally increment or decrement a counter on the table. Add a lambda resolver to read this counter value from the table, and add it to your schema.
  1. Riccardo wrote few years back how to use count , you can find his detail post on following link

Pagination on graphQL