使用Boto将值插入具有整数属性的DynamoDB表中

时间:2019-03-07 12:56:13

标签: python-3.x amazon-dynamodb boto3 dynamodb-queries

我正在使用名为DMS的DynamoDB表,在其中定期更新一些值。因此,我首先将元素中的所有值保存在名为“ response”的变量中。在我的示例中,该元素具有主键220。之后,我将Attribute的值(在本例中为标题522的元素)保存在变量CounterOnePlus中,并添加1。之后,我尝试在列522中更新元素的给定Attribute。这是我的代码:

import boto3
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('DMS')
AverageValue=220
DeltaValue=522
response = table.get_item(
    Key={
        'Average': '%d' % AverageValue,
    }
)
item = response['Item']
CounterOnePlus=int(item['%d' % DeltaValue])+1
print(CounterOnePlus)
table.update_item(
        Key={
                'Average': '%d' % AverageValue,
        },
        UpdateExpression='SET 522 = :val1',
        ExpressionAttributeValues={
                ':val1': CounterOnePlus
        }
)

我面临的问题是我无法保存值。原因是标题的名称,该名称为522。每当我将值插入带有字符串标题(如“ hallo”)的列中时,该值就会更新。使用str(522)将值522更改为字符串不会更改任何内容。我的错误消息如下:

2
Traceback (most recent call last):
  File "TestBoto3.py", line 20, in <module>
    ':val1': CounterOnePlus
  File "/home/ubuntu/.local/lib/python3.6/site-packages/boto3/resources/factory.py", line 520, in do_action
    response = action(self, *args, **kwargs)
  File "/home/ubuntu/.local/lib/python3.6/site-packages/boto3/resources/action.py", line 83, in __call__
    response = getattr(parent.meta.client, operation_name)(**params)
  File "/home/ubuntu/.local/lib/python3.6/site-packages/botocore/client.py", line 357, in _api_call
    return self._make_api_call(operation_name, kwargs)
  File "/home/ubuntu/.local/lib/python3.6/site-packages/botocore/client.py", line 661, in _make_api_call
    raise error_class(parsed_response, operation_name)
botocore.exceptions.ClientError: An error occurred (ValidationException) when calling the UpdateItem operation: Invalid UpdateExpression: Syntax error; token: "522", near: "SET 522 ="

关于我的问题有什么想法吗?谢谢

1 个答案:

答案 0 :(得分:0)

使用ExpresssionAttributeNames(https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.ExpressionAttributeNames.html):

table.update_item(
        Key={
                'Average': '%d' % AverageValue,
        },
        UpdateExpression='SET #DeltaValue = :val1',
        ExpressionAttributeValues={
                ':val1': CounterOnePlus
        },
        ExpressionAttributeNames= {
         "#DeltaValue": str(DeltaValue)  # 522
     }
)