I got this code
public void saveOrUpdateImageRecords(String documentId, List<ImageDetail> imageDetails, LambdaLogger logger) {
DynamoDbTable<ImageDetail> table = enhancedClient.table(System.getenv("COLUMBIA_IMAGES_TABLE"), TableSchema.fromBean(ImageDetail.class));
logger.log("inside saveOrUpdateImageRecords");
for (int i = 0; i < imageDetails.size(); i++) {
ImageDetail imageDetail = imageDetails.get(i);
// Set DocumentId and TrackPosition as they are your keys.
logger.log("image detail " + i);
logger.log(imageDetail.toString());
try {
// Check if the record already exists
ImageDetail itemToCheck = table.getItem(Key.builder()
.partitionValue(documentId)
.sortValue(i)
.build());
if (itemToCheck != null) {
// Update the existing record
logger.log("update");
table.updateItem(imageDetail);
} else {
// Put a new item if it doesn't exist
logger.log("new item");
table.putItem(imageDetail);
}
logger.log("Operation succeeded for image: " );
logger.log(imageDetail.toString());
} catch (DynamoDbException e) {
logger.log("Unable to process image: " + imageDetail.toString());
logger.log(e.getMessage());
// Handle the exception based on your use case
}
}
}
And a test case where imageDetails:List has a single entry. This entry corresponds to an image that already exists in the dynamodb table. As a result of that,
the update clause of the method is executed:
if (itemToCheck != null) {
// Update the existing record
logger.log("update");
table.updateItem(imageDetail);
}
But in the dynamodb table, the entry is duplicated.
Anyone could possibly please point me towards why this is happening?
2
Answers
Looks like this is expected behavior since the value/attribute I update (trackPosition) is also the sort key which means that it has to be unique;
You have DocumentId and TrackPosition as your primary keys. When you update an item you must define the exact key of the item you want to update.
If the keys are new, and the item doesn’t already exist then the default behaviour of UpdateItem is to create a new item. This in your case appears as a duplicate, as you entered a new primary key.