Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Add item to string_set on Dynamodb with Boto3

I have read the official AWS docs and several forums, still I cant find what I am doing wrong while adding item to string_set using Python/Boto3 and Dynamodb. Here is my code:

table.update_item(
                Key={
                    ATT_USER_USERID: event[ATT_USER_USERID]
                },
                UpdateExpression="add " + key + " :val0" , 
                ExpressionAttributeValues = {":val0" : set(["example_item"]) },
            )

The error I am getting is:

An error occurred (ValidationException) when calling the UpdateItem operation: An operand in the update expression has an incorrect data type\"

like image 948
xyz Avatar asked Jun 05 '17 21:06

xyz


Video Answer


1 Answers

It looks like you figured out a method for yourself, but for others who come here looking for an answer:

  1. Your 'Key' syntax needs a data type (like 'S' or 'N')
  2. You need to use "SS" as the data type in ExpressionAttributeValues, and
  3. You don't need "set" in your ExpressionAttributeValues.

Here's an example I just ran (I had an existing set, test_set, with 4 existing values, and I'm adding a 5th, the string 'five'):

import boto3
db = boto3.client("dynamodb")
db.update_item(TableName=TABLE,
               Key={'id':{'S':'test_id'}},
               UpdateExpression="ADD test_set :element",
               ExpressionAttributeValues={":element":{"SS":['five']}})

So before, the string set looked like ['one','two','three','four'], and after, it looked like ['one','two','three','four','five']

like image 70
Joe Stech Avatar answered Oct 18 '22 13:10

Joe Stech