更新在dynamodb中添加属性的项目

时间:2017-10-10 14:07:47

标签: amazon-web-services amazon-dynamodb

是否无法动态地在dynamodb中添加属性?

我尝试时遇到此错误 - " 提供的关键元素与架构不匹配"。

情景 -

{ id : "123",
  imageName : "elephant.jpg"
}

我想添加一个属性 - imagePath:" / path / to / image"以上数据。 我使用了put_item,但如果存在,它会替换旧项目。

我正在寻找解决方案 - 如果id =" 123",则添加imagePath属性,否则在表格中添加新项目。

使用put_item可以实现添加属性,但它将替换现有项目。 如何使用update_item动态地将属性添加到现有数据?(将imagePath附加到给定的json)

我应该使用imagePath更改表的架构,然后使用update_item函数吗?

我们如何使用python实现这一目标?

2 个答案:

答案 0 :(得分:2)

不幸的是,它无法一步到位。但是,它可以通过两个步骤实现: -

1)尝试有条件地插入数据,即如果键值已经存在则不执行任何操作(即插入或更新 - 没有任何反应)

2)如果有ConditionalCheckFailedException,则更新项目

示例代码: -

在下面的代码中,usertable是表名。该表的关键属性是useridscore。您需要相应地更改表结构的以下代码。

另外,我已经分配了键值(作为“Mike”)。您需要根据用例进行相应更改。

from __future__ import print_function # Python 2/3 compatibility
from boto.dynamodb2.exceptions import ConditionalCheckFailedException
from botocore.exceptions import ClientError
from boto3.dynamodb.conditions import Attr
import boto3
import json
import decimal

# 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('usertable')

userId = "Mike"

try :
    response = table.put_item(
    Item={
            'userid': userId,
            'score' : 100,
            'imagePath' : '/path/to/image'        
        },
        ConditionExpression=Attr('userid').ne(userId)        
    )

    print("Conditional PutItem succeeded:")
    print(json.dumps(response, indent=4, cls=DecimalEncoder))
except ClientError as ce :    
    print("Conditional check failed:", ce)
    if ce.response['Error']['Code'] == 'ConditionalCheckFailedException':
        print("Key already exists")
        response = table.update_item(
            Key={'userid': userId, 'score' : 100},
            UpdateExpression="set imagePath = :imagePathVal",
            ExpressionAttributeValues={":imagePathVal" : "/path/to/image" }
        )
        print("Update existing item succeeded:")
        print(json.dumps(response, indent=4, cls=DecimalEncoder))        
    else:
        print("Unexpected error: %s" % e

<强>更新: -

变量id和关键属性RequestId的数据类型应匹配。

答案 1 :(得分:1)

update_item 的最新版本将处理属性创建(如果尚不存在)

import boto3 
from boto3.dynamodb.conditions import Key

def query_status(asset_id, dynamodb, table):
    try:        
        response = table.query(
            ProjectionExpression="#asset_id, status_id" ,
            ExpressionAttributeNames={"#asset_id": "asset_id"},
            KeyConditionExpression=Key('asset_id').eq(asset_id)        
        )
        if response['Items']:
            return response['Items'][0]["status_id"]
    except:
        pass # if attribute does not exists, return None

    
 
def update_asset_status(asset_id, status_id, dynamodb, table):  
    response = table.update_item(
        Key={'asset_id': asset_id},
        UpdateExpression="set status_id=:r",
        ExpressionAttributeValues={':r': status_id},
        ReturnValues="UPDATED_NEW"
    )
    return response



dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('assets')

asset_id='1234'

print("Current Status: ", query_status(asset_id, dynamodb, table))

new_status_id='4'
update_asset_status(asset_id, new_status_id, dynamodb, table)

print("New Status: ", query_status(id, dynamodb, table))
相关问题