I would like to create a table for orders in dynamodb ,each order is composed of (UserID, date, Unique ID, products and total) and I want to query the orders of specific user using userId sorted by date and i want to know how can I choose my partition key ? does it have to be unique and if so how can I make it unique ? in mongodb i would shard my orders based on userID how can i achieve the same using dynamodb ?

- 9,286
- 4
- 28
- 67

- 25
- 1
- 3
-
i would like to confirm, userID is unique right? and what is Unique ID is it the order Id? – Jatin Mehrotra Jan 16 '22 at 07:07
-
did my answer helped? – Jatin Mehrotra Jan 23 '22 at 03:38
-
yes thank you so much i ended up chocing userID as a partition key and date in miliseconds * 1000 + unique 3 digits number as a sort key to make sure each is unique enough – Ahmed gameel Jan 24 '22 at 16:27
1 Answers
Let's say you have a user A with user ID - 1 and user B with user ID - 2 I am assuming A can order multiple times as well as B.
So you can design your table with a composite key ( combination of partition and sort key). In a table that has a partition key and a sort key, it's possible for multiple items to have the same partition key value. However, those items must have different sort key values. All items with the same partition key value are stored together, in sorted order by sort key value.
combination of partition key + sort key will result in a unique order. Here partition key will be userID and orderId will be unique. Hence you can query all orders for a particular user by userId using query operation. and for sorting with date you can use filter expressions in your query operation
if filter expressions does not helpy you with sorting with date then you need to use seperate index based on your createdAt field ( date field). Note :- indexes are costly.
DynamoDB allows for the specification of secondary indexes to aid in this sort of query. Secondary indexes can either be global, meaning that the index spans the whole table across hash keys, or local meaning that the index would exist within each hash key partition, thus requiring the hash key to also be specified when making the query.
Alternate design.
user userId as partition key and CreatedAt as sortKey, yes seconds difference will lead to a unique timestamp and then you can use key condition expression in your query. Querying DynamoDB by date

- 9,286
- 4
- 28
- 67
-
If you can choose the order id to be a KSUID (or similar) then it’ll be both unique and naturally sortable by time. See Alex DeBrie’s writings on exactly this subject. Then the sort key can be ORDER#
and you could also place other aspects of the user in the same item collection too by using a different prefix. – hunterhacker Jan 16 '22 at 18:35