4
votes

Device is my Partition key, table is for putting in multiple different users, under the same Device. However, if I run the following put_item() code, it will overwrite each user if they have the same Device key.

Example: If I put in Monitor, as my device variable, and gomez as my aliasInput variable it runs. Then run it again as Monitor again as my device variable, but craig as my aliasInput it overwrites my gomez entry.

function to input data into my table :

import boto3
import json
import decimal
import time
import datetime

# Helper class to convert a DynamoDB item to JSON.
class DecimalEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, decimal.Decimal):
            if o % 1 > 0:
                return float(o)
            else:
                return int(o)
        return super(DecimalEncoder, self).default(o)


dynamodb = boto3.resource('dynamodb', region_name='us-west-2', endpoint_url="http://localhost:8000")

table = dynamodb.Table('WishListTest')

device = input('What is the Item being requested?\n')
device = device.upper()

aliasInput = input('What is the Alias of the user?\n')
aliasInput = aliasInput.upper()

date = int((time.strftime("%d%m%Y")))
response = table.put_item(
   Item={
        'Device': device,
        'RequestList': {
            'Alias': aliasInput,
            'Date': date
        },
        'AvailableQuanity': 0,
        'ReserveQuanity': 0,

    }
)

print("PutItem succeeded:")
print(json.dumps(response, 
2
Can you please provide the sample output of what do you want to see as a result? Multiple rows for 'Monitor' device, or one record with multiple 'aliasInput''s? - GSazheniuk

2 Answers

3
votes

From the docs: Put item

Creates a new item, or replaces an old item with a new item. If an item that has the same primary key as the new item already exists in the specified table, the new item completely replaces the existing item.

To prevent an overwrite, you need to add a conditional expression specifying that the partition key does not yet exist.

Something like the following should work (sorry, I didn't quite get your key scheme, so you'll have to modify this).

table.put_item(
    Item={'userId': 1, 'productId': 2}, 
    ConditionExpression='userId <> :uid AND productId <> :pid', 
    ExpressionAttributeValues={':uid': 1, ':pid': 3}
)
2
votes

You're looking for update_item(). You should use UpdateExpression because AttributeUpdates is deprecated, but this simple example should get you started:

response = table.update_item(
   Key={
     'Device': device,
   },
   AttributeUpdates={
     'RequestList': {
       'Alias': aliasInput,
       'Date': date
     },
     'AvailableQuanity': 0,
     'ReserveQuanity': 0,
   },
)