Dynamodb put_item()会覆盖数据

时间:2017-12-17 20:16:37

标签: python amazon-web-services amazon-dynamodb

设备是我的分区键,表用于在同一设备下放入多个不同的用户。但是,如果我运行以下put_item()代码,它将覆盖每个用户,如果他们具有相同的设备密钥。

示例:如果我将Monitor作为device变量,gomez作为我的aliasInput变量,则会运行。 然后再次将Monitor再次作为我的device变量再次运行,但craig作为我的aliasInput覆盖我的gomez条目。

将数据输入表格的功能:

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 个答案:

答案 0 :(得分:1)

您正在寻找update_item()。您应该使用UpdateExpression因为AttributeUpdates已被弃用,但是这个简单的示例可以帮助您入门:

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

答案 1 :(得分:1)

来自the docs: 放入项目

  

创建新项目,或将旧项目替换为新项目。如果指定表中已经存在与新项目具有相同主键的项目,则新项目将完全替换现有项目。

为防止覆盖,您需要添加一个conditional expression 指定分区键尚不存在。

类似以下的方法应该起作用(对不起,我还不太了解您的密钥方案,因此您必须对其进行修改)。

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