Dynamodb
DynamoDB
Imagine a HashMap working on a distributed system, enabling us to grow it as much as we need. This is how I like to think about DynamoDB, but it’s not limited to a simple HashMap. Sometimes you need to store multiple values for a single key, and DynamoDB supports that too. Just like if we had Trees in our HashMap values rather than a single values;
The HashMap key is equivalent to DynamoDB partition-key
and the TreeMap key being the sort-key
.
HashMap<String, Object> simpleHashMap = new HashMap<>();
HashMap<String, TreeMap<Double, Object>> HashMapWithMultipleValues = new HashMap<>();
DynamoDB is a fast database because it has simple mechanisms compared to other databases, but it doesn’t mean you will be limited to simple data modeling. You just have to think differently.
Schemaless
DynamoDB is a schemaless database. This means we can add different objects/entities for each key. This feature is essential to enable us to unlock some interesting ways of model our data as Key Overloading
Key Overloading
Now imagine a HashMap that has the customer-id as keys and customer information as values. This is exactly what we mentioned before, but DynamoDB being schemaless, we are not limited to that. We can have different entities being stored there and not only customer-id keys pointing to customer info, but also payment-id pointing to a payment info or anything else, depending on your use case.
When creating a table on DynamDB to take advantage of that feature, we usually don’t name our partition-key or sort-key with entities name as customer-id
, year-month
. We usually just name them as pk
and sk
partition-key
and sort-keys
are sometimes called hash-key
and range-key
respectively. Also, a common convention is to add a prefix in our pk
and sk
values to help us to identify what kind of data we are dealing with and to avoid updates to the wrong entity. ex: customer#96597416-7d37-11ed-a1eb-0242ac120002
pk | sk | Value |
---|---|---|
customer#customer-1 | {“name”: “Jesse Pinkman”, “dob”: “12/12/1983”} | |
payment#customer-1 | payment-month-year#01/2023 | {“status”: “paid” “method”: “credit-card” “credit-card”: “credit-card-123”} |
payment#customer-1 | payment-month-year#02/2023 | {“status”: “pendging”} |