Reputation: 3907
I've started using DynamoDB about 2 weeks ago, and now I've the necessity to get item based on a Sort Column... I've created my table as Token (PK) , CreateTimestamp (sort) but I've find no way of sorting on the CreateTimestamp column. I need this since I need to read the highest attribute that's defined on the last inserted row. How can I do this?
Thanks
Upvotes: 0
Views: 158
Reputation: 567
I think you need to use composite keys, let call them Partition Key (PK) and Sort Key (SK).
To get the all the items in order, first you need to put them in the same partition (same PK value), then create a SK with the condition you wanna sort. For example:
If you wanna sort by date, oldest to newest, you can leverage KSUID
{
"PK": {
"S": "PK"
},
"SK": {
"S": "272XuKFxQEa1VTj5dHEaKXWXBdc"
}
}
272XuKFxQEa1VTj5dHEaKXWXBdc
is create from 2022-03-29 09:02:55.460868
The default query will automatically get the oldest first, in case you wanna get the newest, you can set the param ScanIndexForward
to false
detail.
Otherwise, if you wanna sort as the number increment (0,1,2,3,etc) you need to use the padded number as below:
{
"PK": {
"S": "PK"
},
"SK": {
"S": "0000000"
}
},
{
"PK": {
"S": "PK"
},
"SK": {
"S": "0000001"
}
}
The query can be same as above.
Upvotes: 1