【问题标题】:DynamoDB PutItem does not create new itemDynamoDB PutItem 不创建新项目
【发布时间】:2021-10-16 10:43:55
【问题描述】:

我使用 lambda 来检测我的表中是否有任何 isActive 记录,并使用 put_item 来更新 id(如果有)。

例如,我有一个 ID 为 999999999 的占位符记录,如果我的表查询检测到有一条活动记录(isActive = True),它将在put_item 中包含真实的session_id 和其他数据。

表格记录:

我的 lambda 有以下部分(在我的 cloudwatch 中,if...else 语句正在按预期工作以验证逻辑)。当我复制和粘贴时,请忽略缩进打嗝,代码运行没有问题。

##keep "isActive = True" when there's already an active status started from other source, just updating the session_id to from 999999999 to real session_id

    else:
        count_1 = query["Items"][0]["count_1"] <<< from earlier part of code to retrieve from current count_1 value from the table.
        print(count_1) << get the right '13' value from the current table id = '999999999'
        table.put_item(
           Item={
                    'session_id': session_id,
                    'isActive': True,
                    'count_1': count_1,
                    'count_2': count_2
                },
                ConditionExpression='session_id = :session_id AND isActive = :isActive',
                ExpressionAttributeValues={
                    ':session_id': 999999999,
                    ':isActive': True
                }
                )

但是我的表没有得到新项目,主键session_id 也没有更新。表格仍然如上图所示。

我从documentation 了解到

您不能使用 UpdateItem 更新任何主键属性。 相反,您需要删除该项目,然后使用 PutItem 创建具有新属性的新项目。

但即使put_item 无法更新主键,至少我希望在没有抛出任何错误代码的情况下从我的代码中创建一个新项目?

有人知道发生了什么吗?谢谢

【问题讨论】:

    标签: amazon-web-services aws-lambda amazon-dynamodb


    【解决方案1】:

    我用 ConditionExpression 的不同规范解决了它。是否有多种排错方式,并查明问题来自ConditionExpression

    我做了什么 - 添加boto3.dynamodb.conditions import Key &amp; Attr的导入

    并使用ConditionExpressionConditionExpression=Attr("session_id").ne(999999999)

    并删除旧的 id 项

    table.delete_item(
       Key={
           'session_id': 999999999
       }
    )
    

    这里有其他条件https://boto3.amazonaws.com/v1/documentation/api/latest/reference/customizations/dynamodb.html#ref-dynamodb-conditions

    如果有人想学习其他更好更简单的方法

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-27
      • 2018-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多