Sort key in DynamoDB
What should be it’s structure?
We can not change the Sort key after the table is provisioned. Therefore be careful when creating a sort key structure.
- If your data contains hierarchical (one-to-many) relationships and you want to query at any hierarchy level, use a composite primary key. E.g., Address that contains zip code, postal code, country, city, etc.
The sort key should be structured as follows.
pk: "org#orgId"
sk: "country#region#state#county#city#neighborhood"
Using sort keys for version control
Many applications need to maintain a history of item-level revisions for audit or compliance purposes and to be able to retrieve the most recent version easily. There is an effective design pattern that accomplishes this using sort key prefixes
pk: "doc#docId"
sk: "v0_Audit"
Important note:
Don’t put timestamp or any dynamic value in sort key (sk).
Reason: You can only use pk and sk in BatchGetItem and you cannot use indexes.