python - 如何在 dynamodb 中使用 put_item 在条件表达式中提及地图/字典属性
问题描述
我有一个带有 costcenter 作为哈希键的发电机表,如果团队名称不存在,我想在单个数据库项目/条目中添加新的团队详细信息。
我的代码在 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[\""
解决方案
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']})"
推荐阅读
- php - php 不是电子邮件形式。我在哪里可以在 cpanel 中找到我的 php 错误
- javascript - 逐步切换静音/取消静音视频的音频
- apache-zookeeper - ZooKeeper 与 solrcloud 的 Consul
- java - 非常慢的 JDBC 查询
- java - .split() 和 [\\W] 创建一个额外的空字符串?
- reactjs - History.push() 在注销时重定向到受保护的路由
- ios - 动画没有停止使用 UIView.animate
- python - 如何将数据框列数据添加到另一个数据框中的一系列索引?
- r - 带有 sample.split (caTools) 的 SplitRatio 结果
- ios - Snap Kit 无法使用 startSending 打开 Snapchat