Update element adding attribute to dynamodb

Is it not possible to dynamically add an attribute to dynamodb?

I got this error when I tried - The provided key element does not match the schema .

Script -

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

I want to add the attribute - imagePath: "/ path / to / image" to the above data. I used put_item, but it replaces the old element if it exists.

I am looking for a solution for - If id = "123", then add the imagePath attribute, otherwise add a new element to the table.

Adding an attribute can be achieved with put_item, but it will replace the existing element. How can we dynamically add an attribute to existing data using update_item? (adding imagePath to this json)

Should I change the table schema using imagePath and then use the update_item function?

How can we achieve this with python?

+1
source share
1 answer

Unfortunately, this cannot be done in one step. However, this can be achieved in a two-step process: -

1) Try to insert data conditionally, that is, if the key value is already present, does not perform any operation (i.e., insert or update - nothing happens)

2) If there is a ConditionalCheckFailedException , update the item

Code example:

The usertable code usertable the name of the table. The key attributes of the table are userid and score . You must accordingly modify the code below for your table structure.

In addition, I assigned a key value (like "Mike"). You must modify it accordingly for your use case.

 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 

)

Update: -

The data type of the variable id and the key attribute RequestId must match.

+2
source

Source: https://habr.com/ru/post/1014530/


All Articles