Search code examples
pythonamazon-web-servicesamazon-dynamodbboto3dynamodb-queries

How to delete nested JSON attribute in dynamodb / python


I have a simple dynamodb database that uses "League" as a partition key and "Team" as a sort key to store all roster data under a "Players" attribute field that uses a JSON format. I would like to access and delete a specific player (Larry Bird or Jayson Tatum in this case), however, I am having trouble accessing the schema correctly to delete the specific key and values, especially given that Players.Jayson Tatum wont work because it is two separate words. Here is the basic skeleton code for the function so far:

def lambda_handler(event, context):

    newLeague = None
    newTeam = None
    newPlayer = None
    statusCode = 200

    if checkKey(event, 'League'):
        newLeague = event['League']
    
    if checkKey(event, 'Team'):
        newTeam = event['Team']
    
    if checkKey(event, 'Player'):
        newPlayer = event['Player']

    if newLeague != None and newTeam != None and newPlayer != None:
        retrievedData = table.delete_item(
           Key = {
               'League': newLeague,
               'Team': newTeam,
           }
        )

Database layout in Dynamodb for reference

Database layout in Dynamodb for reference


Solution

  • Removing a nested item in DynamoDB can be done by using the REMOVE-expression in the update_item-method:

    client.update_item(
        TableName=table_name,
        Key={"League": {"S": "NBA"}, "Team": {"S": "Celtics"}},
        UpdateExpression="REMOVE Players.#p",
        ExpressionAttributeNames={"#p": "Larry Bird"},
    )
    

    Note the ExpressionAttributeNames, to get around the fact that the player name has a space in it.

    Adding a player is done in a similar fashion:

    client.update_item(
        TableName=table_name,
        Key={"League": {"S": "NBA"}, "Team": {"S": "Celtics"}},
        UpdateExpression="SET Players.#p = :v",
        ExpressionAttributeNames={"#p": "Larry Bird"},
        ExpressionAttributeValues={":v": {"M": {..}}}
    )