How to create secondary indexes with GraphQL and AWS AppSync

This post assumes you have a general understanding of GraphQL, AppSync, and DynamoDB.

Phil Andrews
The Startup
Published in
2 min readSep 16, 2019

--

When working with AppSync you’re usually tied to DynamoDB as a data store. This can be tricky due to the nature of NoSQL. Figuring out your data access patterns early will help you down the line. But if you don’t it’s relatively easy to update your schema on the fly.

For instance, if you realize that you will actually need to query by a particular field on a regular basis and that field isn’t the hash key you’ll need a global secondary index (GSI). This is standard stuff in DynamoDB but is abstracted when we move up the stack to AppSync, which handles the majority of indexing and provisioning for you behind the scenes.

So if you find yourself in need of a GSI for a table that has already been created go to your schema.graphql file.

Within the model that you want to create an index on we’ll add the keyword key to our type. Changing this…

type BoxScore @model {
id: ID!
gameId: String!
homeTeamId: String!
awayTeamId: String!
}

To this…

type BoxScore @model 
@key(name: “byHomeTeam”, fields: [“homeTeamId”], queryField: “boxScoresByTeam”)
{
id: ID…

--

--