Appending list not working for AWS DynamoDB using Python boto3

Question:

I’m trying to append a value to a DynamoDB table entry:

{
 "id": "1",
 "history": [
  "638380895-8"
 ],
 "currentbooks": "",
 "email": "[email protected]",
 "name": "Osborne Comford"
}

I’m trying to write the code to add a string entry to ‘history’ array.

Following is my python code:

usersTable = dynamodb.Table("users")
booksTable = dynamodb.Table("books")
bookisbn = event['isbn']
response = usersTable.update_item(
    Key={
        'id': userid,
    },
    UpdateExpression="set history=list_append(history, :s)",
    ExpressionAttributeValues={ 
        ':s': bookisbn

    },
    ReturnValues="UPDATED_NEW"
)

It’s giving me the error:

"errorMessage": "An error occurred (ValidationException) when calling the UpdateItem operation: Invalid UpdateExpression: Incorrect operand type for operator or function; operator or function: list_append, operand type: S"
Asked By: Mathew Dony

||

Answers:

list_append works with 2 lists:

list_append(list1, list2)

You need to pass the update expression along with the type of the element that you’re adding i.e. "L" for a list:

response = usersTable.update_item(
    Key={
        'id': userid,
    },
    UpdateExpression="set history=list_append(history, :isbn)",
    ExpressionAttributeValues={ 
        ':isbn': {"L": [ { "S" : isbn } ]} # ensure you pass a list

    },
    ReturnValues="UPDATED_NEW"
)

See the docs for example.

Answered By: rdas
    response = usersTable.update_item(
    Key={
        'id': userid,
    },
    UpdateExpression="set history=list_append(history,:isbn)",
    ExpressionAttributeValues={ 
        ':isbn': [bookisbn]

    },
    ReturnValues="UPDATED_NEW"
)

This is the correct solution…

Answered By: Mathew Dony