Member-only story
Sorting data in AWSAmplify and DynamoDB with @key directive
To solve this, we have to use Global Secondary Index in DynamoDB and the new @key directive.
Back to schema.graphql and add the @key directive.
type Incident @model @key(name: "ByUser", fields: ["username", "timestamp"], queryField: "incidentsByUser") { id: ID location: String timestamp: AWSTimestamp username: String message: String }
Here we are creating a custom index named: “ByUser”.
It takes 2 fields, username is the partition-key while timestamp is the sort-key. We also tell Amplify to create another query with the name “incidentsByUser” for us.
Run [amplify push] again to update the backend
AppSync will create the Global Secondary Index (GSI) in your DynamoDB. It will go through a backfilling process for any existing data.
Now go back to AppSync Console and try “listIncidents” again
Oh no. The result is still out of order.
Open up the Schema section on the right and you will notice a new Query called: “incidentsByUser”. We want to use this query instead of the “listIncidents” query.
Volia, data comes back in order!