I am trying to create a structure that lists comments for a post with postId
ordered w.r.t. their lastChangeTime
descending.
The model in the schema is shared below.
type Comment {
id: ID!
postId: String!
user: String!
lastChangeTime: String
commentBody: String
}
It has a backing DynamoDB table and generic CRUD resolvers for it already.
And id
field is the primary key in the table.
I plan to build a query as follows:
{
"version": "2017-02-28",
"operation" : "Query",
"index" : "postId-index",
"query" : {
"expression": "post = :postId",
"expressionValues" : {
":postId" : {
"S" : "${ctx.args.postId}"
}
}
},
"limit": $util.defaultIfNull($ctx.args.first, 20),
"nextToken": $util.toJson($util.defaultIfNullOrEmpty($ctx.args.after, null)),
"scanIndexForward": false
}
To make it work, how should I add the Global Secondary Index (GSI) on postId
(i.e. postId-index
)?
Should I add a sort key on lastChangeTime
when defining it and it would be ok? Or lastChangeTime
field requires its own separate index to be sorted through?
It is easy. You can do it in two different ways or you can use both ways to have better flexibility. ( if you already resolved it I hope it will help someone else ).
Doing it this way you can set sortDirection dynamically using query arguments.
Detailed code is given below. Before that please note this point.
First point is re your Comment type - you are using
This is not the best way to set up your Comment type linked to a Post.
Better way is:
If you do this your DynamoDB table will have structure similar to one shown below ( from this AWS webpage).
( In your case UserId would be PostId and GameTitle would be CommentID )
This way, because all comments would be recorded next to each other (under same PostId ) AppSync response time would be much faster.
In AppSync docs page they also used this example:
Then in your schema you can define following types:
You can use both - Option 1 and Option 2 and use both.
Full schema code is here ( expand the snippet below ):
In request mapping template:
In response mapping template:
In request mapping template:
In response mapping template:
That is it.
Now you can use all of following queries: