Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update items based on just the partition key?

Our table has a composite primary key. There are a few use cases where we need to update the items based on just the partition key.

partitionKey    sortKey
------------    ---------
10020525        208025117-xxxxx-153068323-208025401
10020525        208025117-208025475-153068323-208025401

Following is how I am currently updating: (Using Java)

UpdateItemRequest updateItemRequest = new UpdateItemRequest().withTableName("table").withKey(attMap);
UpdateItemResult updateItemResult = amazonDynamoDB.updateItem(updateItemRequest);

The 'attMap' already has the 'partitionKey' and 'sortKey'. Therefore, it does take care of updating the record matches the partition and sort key.

In a few cases (where there is a 'xxxxx' in the sort key), I want to update based on just the partitionKey.

Let me know if something is not clear. Would be happy to explain further.

like image 233
miserable Avatar asked Oct 17 '25 16:10

miserable


2 Answers

Updating multiple items at once is not supported by DynamoDB. For this reason you cannot make update requests with just the partition key unless your table schema only has a partition key and no sort key.

This is probably not the answer you were hoping for but it is how DynamoDB works. You have to consider your use-cases carefully and choose a schema that works, or consider different database solutions.

like image 98
Mike Dinescu Avatar answered Oct 22 '25 06:10

Mike Dinescu


By default Dynamo DB does not allow such updates, you need to provide both partition key and sort key in update operation. One thing worth trying is to use transaction request so that you include all items which match the partition key. This approach works when you have limited number of records with fits the SDK API limitations for single transaction request. Here is an example:

List<Update> updates = records.stream()
            .map(record -> Update.builder()
                    .tableName(this.someTable)
                    .key(ImmutableMap.of(
                         PART_KEY, AttributeValue.builder().s(record.partKey).build(), 
                         SORT_KEY, AttributeValue.builder().s(record.sortKey).build()))
                    .build()).collect(Collectors.toList());

Collection<TransactWriteItem> actions = new ArrayList<>();
updates.stream().forEach(update -> 
       actions.add(TransactWriteItem.builder().update(update).build()));

TransactWriteItemsRequest updateProfileTransaction = TransactWriteItemsRequest
            .builder()
            .transactItems(actions)
            .build();
like image 32
Alex Avatar answered Oct 22 '25 04:10

Alex