4
votes

When creating a composite key in DynamoDB with a hash and range/sort key, it seems really useful to store creative string values in the sort key (e.g. “Details-123456-foo”, where each segment in that value can be something meaningful for that record). The docs seem to navigate you in that direction as well when designing the schema.

That said, does it make sense to name the sort key something generic, like “sortKey” or “rangeKey” instead of something specific (e.g. “createTimestamp”) to give you the flexibility of storing all sorts of data for the same hash key, thus maintaining fast data access when using the “query” API with the hash/sort keys?

1
I personally prefer the specific version eg. username_type or UsernameType because the code is self explanatory later.Adrian Praja

1 Answers

5
votes

Yes, it's a best practice for DynamoDB to use generic names for the primary key and the sort key.

When you use DynamoDB as intended, you store items of different types in a single table. Item-type specific key names for primary key and sort key don't work with that. The same applies when you use GSI overloading.

Let's take the use case of a blog as example, where you have posts and comments you want to store in the same DynamoDB table. In this case you'd have some kind of unique id for each post and comment. Instead of naming the primary key "post_id" you'd call it generically (e.g. just "id") and store posts and comments by prepending their type to the value ("post_1", "post_2", "comment_1", ...). The same applies for the sort key as well, because depending on the key type you might want to sort by different criteria.