Reputation: 63
I have this DynamoDb table:
ID | customer_id | product_code | date_expire |
---|---|---|---|
3 | 12 | TRE65GF | 2023-11-15 |
5 | 12 | WDD2 | 2023-11-15 |
4 | 44 | BT4D | 2023-06-23 |
What is the best way, in DynamoDb, to update the "date_expire" field to all customers with the same customer_id?
For example ,I want to set the date_expire to "2023-04-17" to all data with customer_id ="12".
Should I do a scan of the table to extract all the "IDs" and then a WriteRequestBatch? Or is there a quicker way, like normal sql queries ("update table set field=value where condition=xx")?
Upvotes: 1
Views: 140
Reputation: 19753
If this is a common use-case, then I would suggest creating a GSI with a partition key of custome_id
customer_id | product_code | date_expire | ID |
---|---|---|---|
12 | TRE65GF | 2023-11-15 | 3 |
12 | WDD2 | 2023-11-15 | 5 |
44 | BT4D | 2023-06-23 | 4 |
SELECT * FROM mytable.myindex WHERE customer_id = 12
First you do a Query
on the customer_id to give you back all the customers data, then you have a choice on how to update the data:
UpdateItem
Depending on how many items returned it may be best to just iterate over them and call an UpdateItem on each item. UpdateItem is better than the PutItem or BatchWriteItem as its an upsert and not an overwrite, which means you will be less likely to corrupt your data due to conflicts/consistency.
BatchWriteItem
If you have a large amount of items for a customer, BatchWriteItem may be best for speed, where you can write batches of up to 25 items. But as mentioned above, you are overwriting data which can be dangerous when all you want to do is update.
TransactWriteItems
Transactions give you the ability to update batches of up to 100 items at a time, but the caveat is that the batch is ACID compliant, meaning if one item update fails for any reason, they all fail. However, based on your use-case, this may be what you intend to happen.
PHP examples are available here.
Upvotes: 1