这是我的示例代码
import boto3
import os
ENV = "dev"
DB = "http://awsservice.com"
REGION = "us-east-1"
TABLE = "traffic-count"
def main():
os.environ["AWS_PROFILE"] = ENV
client = boto3.resource("dynamodb", endpoint_url=DB, region_name=REGION)
kwargs = {'Key': {'id': 'D-D0000012345-P-1'},
'UpdateExpression': 'ADD #count.#car :delta n SET #parentKey = :parent_key, #objectKey = :object_key',
'ExpressionAttributeValues': {':delta': 1, ':parent_key': 'District-D0000012345', ':object_key': 'Street-1'},
'ExpressionAttributeNames': {'#car': 'car', '#count': 'count', '#parentKey': 'parentKey', '#objectKey': 'objectKey'}}
client.Table(TABLE).update_item(**kwargs)
if __name__ == "__main__":
main()
我想要实现的是:
通过单个 API 调用(在此update_item
中),我希望能够
- 如果项目未退出,则使用地图
count
创建项目并使用{'car': 1}
对其进行初始化,并将字段设置为parent_key
和object_key
。
或
- 如果
- 该项目已存在,请将字段更新为
{'car': 2}
(如果原始计数为 1)
以前,如果我没有使用地图,我可以用这个表达式成功更新,
SET #count = if_not_exist(#count, :zero) + :delta,
#parentKey = :parent_key, #objectKey = :object_key
但是我收到此错误:
botocore.exceptions.ClientError: 发生错误 (验证异常)调用 UpdateItem 操作时: 更新表达式中提供的文档路径对于更新无效
哪个文档路径导致问题?我该如何解决它?
对于那些以类似错误登陆此页面的人:
The document path provided in the update expression is invalid for update
原因可能是:
for the item on which the operation is being performed,
this attribute (count, for example) is not yet set.
考虑到问题中的示例代码, 异常可能来自count
为空或未设置的所有项目。因此,更新查询不知道需要在哪个map
设置或更新新值(例如汽车)。
在问题中,OP 一开始是可能的,因为该属性不是map
,并且该过程只是将值设置为按原样count
。它不会尝试访问未知映射的键来设置值。
这可以通过捕获异常来处理。例如:
from botocore.exceptions import ClientError
...
try:
response = table.update_item(
Key={
"pk": pk
},
UpdateExpression="set count.car = :c,
ExpressionAttributeValues={
':c': "some car"
},
ReturnValues="UPDATED_NEW"
)
except ClientError as e:
if e.response['Error']['Code'] == 'ValidationException':
response = table.update_item(
Key={
"pk": pk
},
UpdateExpression="set count = :count",
ExpressionAttributeValues={
':count': {
':c': "some car"
}
},
ReturnValues="UPDATED_NEW"
)