A partition key is a DynamoDB attribute used in a table’s primary key. If it is the only key attribute, its value uniquely identifies an item. You need that value to retrieve, update, or delete the item. DynamoDB maintains a hash-based index for the partition key, so a lookup requires an exact value. section 12.7 section 12.7.1
Choose the key to match how the application retrieves data:
- For users fetched by ID, make the unique `uid` the sole primary-key attribute of `todo-user`. section 12.2.1
- For tasks listed by user, give `todo-task` a partition key of `uid` and a sort key of `tid`. Several tasks can share a `uid`, but each `uid`–`tid` combination must be unique. section 12.2.2
$ aws dynamodb create-table --table-name todo-user \ #1 --attribute-definitions AttributeName=uid,AttributeType=S \ #2 --key-schema AttributeName=uid,KeyType=HASH \ #3 --provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5 #4 #1 Prefixing tables with the name of your application will prevent name clashes in the future. #2 Items must at least have one attribute uid of type string. #3 The partition key (type HASH) uses the uid attribute. #4 You’ll learn about this in section 12.11.
The AWS CLI table definition declares `uid` as a string attribute and assigns it `KeyType=HASH`, DynamoDB’s key-schema designation for a partition key. section 12.2.1
$ aws dynamodb create-table --table-name todo-task \ --attribute-definitions AttributeName=uid,AttributeType=S \ #1 AttributeName=tid,AttributeType=N \ --key-schema AttributeName=uid,KeyType=HASH \ AttributeName=tid,KeyType=RANGE \ #2 --provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5 #1 At least two attributes are needed for a partition key and sort key. #2 The tid attribute is the sort key.
The task-table definition adds `tid` with `KeyType=RANGE` while retaining `uid` as `HASH`. section 12.2.2
Use `getItem` with `uid` to fetch one user; fetching one task requires both `uid` and `tid`. To list a user’s tasks, use `query` with a key condition such as `uid = :uid`. A partition-key condition uses an exact match; a sort-key condition can narrow the results by value or range. The sort key cannot be queried on its own. section 12.4.1 section 12.7.2
Query tasks another way
A `uid` partition key answers “which tasks belong to this user?” It does not directly answer “which tasks are shopping tasks across users?” A global secondary index can use `category` as its partition key and `tid` as its sort key for that query. The index adds storage and write-capacity costs, and its updates are eventually consistent. section 12.4.3 section 12.4.4









