Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DynamoDB - Sort key attribute name

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?

like image 253
tbehunin Avatar asked Nov 17 '19 05:11

tbehunin


People also ask

Can I query by sort key DynamoDB?

You can not query only using a Sort Key. You need to specify a partition key to perform query operations. Else, you need to create a global secondary index or perform a scan operation.

Does DynamoDB sort key need to be unique?

In a DynamoDB table, the combined partition key value and sort key value for each item must be unique. However, in a local secondary index, the sort key value does not need to be unique for a given partition key value.

Can we have multiple sort keys in DynamoDB?

Generally in DynamoDB you can create Local Secondary Indexes if you need alternative sort key: To give your application a choice of sort keys, you can create one or more local secondary indexes on an Amazon DynamoDB table and issue Query or Scan requests against these indexes.

How do I change the sort key in DynamoDB?

Can DynamoDB sort key be updated? No. Similarly to the partition key, sort key cannot be changed after the table is provisioned.


1 Answers

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.

like image 78
Dunedan Avatar answered Oct 01 '22 23:10

Dunedan