首页 > 解决方案 > 使用 boto3 有条件地将项目插入到 dynamodb 表中错误属性名称是保留关键字

问题描述

如果项目(状态)不存在,我将调用此函数来放置项目,我在这里指的是:如何使用 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

有什么建议来处理这个吗?

标签: pythonamazon-web-servicesamazon-dynamodbboto3dynamodb-queries

解决方案


这就是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

推荐阅读