Search code examples
amazon-web-servicesamazon-dynamodbboto3

How to only update one column value in Dynamodb using updateItem and create a new row with additional columns?


I'm using python and boto3 to fetch some data from a different source and want to only update one column in the dynamodb table.

However, if the primary key or the row doesn't exist in Dynamodb, I want that entire row to be created.

Wondering what I might be doing wrong here?

I'm specifying the single column for the UpdateExpression that I want to be updated and included that as the ExpressionAttributeNames and ExpressionAttributeValues. This works just fine if I'm updating a row of data that already exists in dynamo.

  ExpressionAttributeNames = {
    '#amount': 'amount',
  }
  
  ExpressionAttributeValues = {}

  for request in requests:
    ExpressionAttributeValues[f":{key}"] = val

    response = table.update_item(
      Key={ 'id': primaryKey },
      UpdateExpression= 'set #amount = :amount',
      ExpressionAttributeNames=ExpressionAttributeNames,
      ReturnValues= 'ALL_NEW',
      ExpressionAttributeValues=ExpressionAttributeValues
    )

If the row doesn't exist though, it only creates the id and the amount columns when the additional rows can include other columns for example {item, count, color, etc} and I need those additional columns of data to be created when it doesn't exist in Dynamo. The only solution I can think of is having this be a conditional and using conditionExpression to only update if primaryKey exists, then depending on the response, we will decide whether it's necessary to create the row. We will need to have a diff ExpressionAttributeNames and ExpressionAttributeValues to capture all of the columns for the rows. Is this correct?

Any help here is greatly appreciated!


Solution

  • You either have to set all values when you update the item (1 request), or use a condition expression on the item existing. If it fails the condition, you then do a PutItem will all values (2 requests).