DynamoDB is highly scalable NoSQL database offering high availability. By leveraging global table feature you can replicates data across many regions automatically.
Keys
There are 2 types of keys in DynamoDB:
- Partition
- Index that gives a constant time lookup for items.
- Can be string, numeric or binary value.
- Used as hash value to allow items location in constant time regardless of table size.
- Sort
- Optional. Also known as Range Key.
- Allows to search and sort items within partition.
- Used when Partition Key is not unique or there is a need to perform range-like queries base off some other value
- One of common use cases is to use a timestamp as sort key to find items within specific date range.
- Another use case is to use string value to find data in hierarchical relationships.
Primary key
- Required in any DynamoDB table.
- Can be Partition Key if it will be unique.
- If there are repeating values in Partition Key there should be a Sort Key configured as well. In such case the combination of two will make a Primary Key.
- It means that when columns are defined there should be a decision made if Sort Key is needed or Partition Key will be enough.
Consider example below. In one of my projects I had to organize storing multiple subscriptions per customer account. In this case Account ID serves as a Partition Key. Subcription’s ID combined with the date of registration serves as a Sort Key.
Secondary Global Index (SGI)
- Enables additional access patterns in table and helps to avoid full-scan operations.
- Allows to have a constant lookup time by attributes (columns) that are not a Partition Key.
- When defining a new SGI there is a need to select new Partition Key. As the result table gets cloned and stays in sync with the primary one.
- Addition / deletion of items to primary table will be propagated to secondary tables.
- Due to the async nature of such replication (eventual consistency) it’s possible to have race conditions with stale data returned.
- Can be created and deleted at any time.
- It’s possible to define Projections when creating GSI.
- Meaning it’s possible select a subset of attributes instead of all of them.
Local Secondary Index (LSI)
- Must be created at the same time the table is created.
- Effectively they allow having another Sort Key using the same Partition Key.
References