gpt4 book ai didi

python - 如何使用 ConditionExpression 检查非键属性是否已存在于 dynamodb 中?

转载 作者:太空狗 更新时间:2023-10-29 23:58:07 28 4
gpt4 key购买 nike

只有当用户 ID、电子邮件和用户名不存在(希望它们是唯一的)时,我才想插入到用户表中。
userId 是主键(哈希键,数据类型 - 数字)。
用户名和电子邮件是非关键属性(均为字符串)。

以下是我的尝试:

response = userTable.put_item(
Item={
'userId': userIdNext,
'accType': 0,
'username': usernameInput,
'pwd': hashedPwd,
'email': emailInput
},
ConditionExpression = "(attribute_not_exists(userIdNext)) AND (NOT (contains (email, :v_email))) AND (NOT (contains(username, :v_username)))",
ExpressionAttributeValues={
":v_email": emailInput,
":v_username": usernameInput
}
)

我试图从这里遵循逻辑运算符和条件表达式的 aws 文档:AWS Conditional Expressions

但它每次都会插入到表中,即使用户名或电子邮件已经存在于数据库中。
(我正在提供新的 userIdNext,因为它是主键,不能重复)

我正在使用 Python 实现 boto3

最佳答案

dynamodb 只能强制哈希范围表键的唯一性(而不是全局二级索引键)

在您的情况下,有 2 个选项:

1) 在应用程序级别强制执行 - 查询记录,并查找是否重复

2) 添加另一个具有哈希/范围值的 dynamodb 表(可以强制唯一性),您可以在将项目放入主表之前查询此表

3) 使用应用程序锁(memcache..)

4) 不要使用 dynamodb(也许它不能满足你的要求)

在这里向您推荐答案:

DynamoDB avoid duplicate non-key attributes

DynamoDB consistent reads for Global Secondary Index

关于python - 如何使用 ConditionExpression 检查非键属性是否已存在于 dynamodb 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35571700/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com