49

With contrast to primary key, composite key and candidate key, what is a partition key and a sort key in dynamodb?

1

1 Answer 1

87

The partition key is used for partitioning the data. Data with the same partition key is stored together, which allows you to query data with the same partition key in 1 query.

The (optional) sort key determines the order of how data with the same partition key is stored. Using a clever sort key allows you to query many items in 1 query.

An example: let's say I'm storing logging data for several applications. My partition key could be the Application Name, and the sort key the timestamp of the log. This allows me to query all logs of a particular application of the last hour in 1 query, using the BEGINS WITH operator, or even all the logs of last Wednesday for an application, by using the BETWEEN operator.

The partition key + the optional sort key form the primary key of the table, so they must be unique. Additionally, they are immutable.

The choice of your partition key and sort key should be based on your most important access pattern. If you have other access patterns, you can accommodate for them by using Global Secondary Indexes, but this comes with a cost.

6
  • Does this same principal, of returning more data in one query by using an appropriate partition and sort key, apply to secondary indexes as well? Dec 4, 2019 at 11:56
  • @RichardDunn Secondary Indexes work mostly the same way. There are Local Secondary Indexes, which come with a couple of caveats I believe are bad enough to normally not use them at all: - Cannot add/modify after creating the table, - if you have any LSI's in your table, the total size of your partition is limited to 10 GB. (Without LSI's there is no practical limit. Source: docs.aws.amazon.com/amazondynamodb/latest/developerguide/…)
    – wvdz
    Dec 4, 2019 at 14:17
  • @RichardDunn Global Secondary Indexes (GSI's) don't come with these caveats. For those, the only difference with the primary key is that they cannot be queried with Strong consistency, only with eventual consistency.
    – wvdz
    Dec 4, 2019 at 14:21
  • Thanks, that's really useful info. Dec 4, 2019 at 15:46
  • Just wondering if using application name as the partition key in this particular instance (for logging) is not a very good idea and will lead to very few partitions that are extremely large, and thus will exhaust RCU/WCU pretty quickly?
    – Art
    Apr 28 at 6:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.