When creating a Dynamodb table select Primary Keys and Local Secondary Indexes (LSIs) so that a Query operation returns the items you want.
Query operations only support an equal operator evaluation of the Primary Key, but conditional (=, <, <=, >, >=, Between, Begin) on the Sort Key.
Scan operations are generally slower and more expensive as the operation has to iterate through each item in your table to get the items you are requesting.
Example:
Table: CustomerId, AccountType, Country, LastPurchase
Primary Key: CustomerId + AccountType
In this example, you can use a Query operation to get:
- A CustomerId with a conditional filter on AccountType
A Scan operation would need to be used to return:
- All Customers with a specific AccountType
- Items based on conditional filters by Country, ie All Customers from USA
- Items based on conditional filters by LastPurchase, ie All Customers that made a purchase in the last month
To avoid scan operations on frequently used operations create a Local Secondary Index (LSI) or Global Secondary Index (GSI).
Example:
Table: CustomerId, AccountType, Country, LastPurchase
Primary Key: CustomerId + AccountType
GSI: AccountType + CustomerId
LSI: CustomerId + LastPurchase
In this example a Query operation can allow you to get:
- A CustomerId with a conditional filter on AccountType
- [GSI] A conditional filter on CustomerIds for a specific AccountType
- [LSI] A CustomerId with a conditional filter on LastPurchase
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…