![](/img/trans.png)
[英]How do I conditionally insert an item into a dynamodb table using boto3
[英]Conditionally insert an item into a dynamodb table using boto3 Error Attribute name is a reserved keyword
如果项目(状态)不存在,我正在调用此函数来放置项目,我从这里指的东西: 如何使用 boto3 有条件地将项目插入到 dynamodb 表中..
def put_items_if_doesnt_exist():
dynamodb = boto3.resource('dynamodb',region_name='us-east-1')
try:
table = dynamodb.Table('awssolutions-ssm-hybrid-table')
response = table.put_item(
Item={
'name':'Execution',
'state': 'Locked',
},
ConditionExpression='attribute_not_exists(state) AND attribute_not_exists(name)'
)
except ClientError as e:
# Ignore the ConditionalCheckFailedException
if e.response['Error']['Code'] != 'ConditionalCheckFailedException':
raise
这里的问题是状态是一个保留字,因此它失败并显示错误:
[ERROR] ClientError: An error occurred (ValidationException) when calling the PutItem operation: Invalid ConditionExpression: Attribute name is a reserved keyword; reserved keyword: state
有什么建议可以处理这个问题吗?
这就是ExpressionAttributeNames
用武之地,它们允许您使用保留名称。 您只需添加一个带有#
前缀的占位符,并在ExpressionAttributeNames
参数中指定其值。
def put_items_if_doesnt_exist():
dynamodb = boto3.resource('dynamodb',region_name='us-east-1')
try:
table = dynamodb.Table('awssolutions-ssm-hybrid-table')
response = table.put_item(
Item={
'name':'Execution',
'state': 'Locked',
},
ConditionExpression='attribute_not_exists(#state) AND attribute_not_exists(#name)',
ExpressionAttributeNames={"#state": "state", "#name", "name"}
)
except ClientError as e:
# Ignore the ConditionalCheckFailedException
if e.response['Error']['Code'] != 'ConditionalCheckFailedException':
raise
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.