- Newest
- Most votes
- Most comments
To do it in a performant way you might have to keep track of the count (usually in the "parent"). For example, you can add a property "count" in the Countries and keep it updated (immediately or periodically).
To retrieve the count of items in the "CITIES" table for a specific country, such as "Spain," using AWS AppSync and DynamoDB, you can follow these steps:
Define GraphQL Schema: In your AppSync API, define a GraphQL schema that includes the necessary types and queries. For example:
type City { id: ID! name: String! country: String! } type Query { getCitiesCountByCountry(country: String!): Int! }
Create Resolver: Create a resolver for the getCitiesCountByCountry
query that uses a DynamoDB resolver template. In the resolver template, use the scan
operation to count the items with the specified country:
{ "version": "2017-02-28", "operation": "Scan", "filter": { "expression": "country = :country", "expressionValues": { ":country": $util.dynamodb.toDynamoDBJson($context.arguments.country) } }, "select": "COUNT" }
Invoke Query: Use the AppSync GraphQL API to invoke the getCitiesCountByCountry
query, passing the desired country (e.g., "Spain") as an argument.
For returning the total count of items in a table using the Amplify app, please check these steps.
Using Amplify Libraries: If you want to retrieve the total count of items in a table directly from your Amplify app (not through AppSync), you can use the Amplify DataStore library to interact with your DynamoDB tables. You can use the count
method to fetch the total count of items in a specific table:
import { DataStore } from '@aws-amplify/datastore'; import { City } from './models'; // Replace with your model import const totalCount = async () => { const citiesCount = await DataStore.query(City); console.log('Total count of cities:', citiesCount.length); }; totalCount();
Relevant content
- asked a year ago
- AWS OFFICIALUpdated 2 years ago
- AWS OFFICIALUpdated 3 years ago
- AWS OFFICIALUpdated 3 years ago
- AWS OFFICIALUpdated 3 years ago
Wouldn't that increase the number of API requests to make? I thought about what you suggested and it will work well with the COUNTRIES and CITIES since they are unlikely to change oftenly. However, what about other scenarios like USER and BLOGS?
For example, I will need to have 2 mutations (i.e. createBLOG and updateUSER, to create the blog in the BLOG table and update the user's "count_total_blogs" field in the USER table respectively). Would it be possible to do this via a single mutation/API request? Just trying to be optimal here, if AppSync doesn't allow a COUNT of items I will consider your solution but also like to know what other options there are.