首页 > 解决方案 > 如何在 dynamodb 中使用 put_item 在条件表达式中提及地图/字典属性

问题描述

我有一个带有 costcenter 作为哈希键的发电机表,如果团队名称不存在,我想在单个数据库项目/条目中添加新的团队详细信息。

显示团队添加的 db 项目的示例图像

我的代码在 lambda 中执行。

import json
import boto3


dynamodb_res = boto3.resource('dynamodb', region_name='ap-south-1')
table=dynamodb_res.Table('sampletable')

def lambda_handler(event, context):
    def add_team():
        table.put_item(
        Item={
            'COSTCENTER': event['costcenter'],
            'Teams': {
                 event['teamName']: {
                     "EMAIL": event['email'],
                     "GROUP": event['group']     
                }
            }
        },
        ConditionExpression= "attribute_not_exists(Teams[event['teamName']])"
        )
    add_team()

参数event['teamname']包含团队名称信息。参数在 lambda 的配置测试事件控制台中。

我的参数:

{
  "teamName": "team1",
  "costcenter": "0000",
  "email": "sample@samplename.com",
  "group": "devops"
}

只有在不存在时才需要添加“team1”团队。运行代码后出现以下错误。

"errorType": "ClientError",
  "errorMessage": "An error occurred (ValidationException) when calling the PutItem operation: Invalid ConditionExpression: Syntax error; token: \"event\", near: \"[event[\""

标签: pythonpython-2.7amazon-dynamodbboto3

解决方案


ConditionExpression您可以提供静态参数或所谓的表达式属性参数进行替换,如下所示:

  • attribute_not_exists(Teams.team1)(静止的)
  • attribute_not_exists(:team)(表达式属性)

在后一种情况下,您需要为ExpressionAttributeValues您的 boto3 调用提供单独的参数。

这是关于它的文档,在 boto3 文档中引用:https ://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.ConditionExpressions.html

在您的情况下,我将尝试使用以下方法扩展参数名称f-string

ConditionExpression=f"attribute_not_exists(Teams.{[event['teamName']})"


推荐阅读