如何使用ConditionExpression检查dynamodb中是否已经存在非键属性? [英] how to check if non-key attribute already exists in dynamodb using ConditionExpression?

查看:23
本文介绍了如何使用ConditionExpression检查dynamodb中是否已经存在非键属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想在 userId、email 和 username 不存在时插入 users 表(希望这些是唯一的).
userId 是主键(哈希键,数据类型 - Number ).
用户名和电子邮件是非关键属性(都是字符串).

这是我的尝试:

response = userTable.put_item(项目={'userId': userIdNext,'acctype': 0,'用户名':用户名输入,密码":哈希密码,电子邮件":电子邮件输入},ConditionExpression = "(attribute_not_exists(userIdNext)) AND (NOT (contains (email, :v_email))) AND (NOT (contains(username, :v_username)))",表达式属性值={":v_email": emailInput,":v_username": 用户名输入})

我尝试从此处遵循逻辑运算符和条件表达式的 aws 文档:AWS 条件表达式

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

我正在使用 Python 实现 boto3

解决方案

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

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

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

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

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

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

在此处推荐您的答案:

DynamoDB 避免重复的非键属性p>

全球二级索引的DynamoDB一致性读取

I want to insert into users table only if userId, email and username does not exist ( want these to be unique).
userId is the primary key ( Hash key, data type - Number ).
username and email are non-key attributes ( both string ).

Here is how i tried:

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
}
)

I tried to follow the aws documentation for logical operators and condition expression from here: AWS Conditional Expressions

But it is inserting everytime into table even if username or email already exists in the db.
( i am giving new userIdNext as it is primary key and cannot be a duplicate )

I am using Python implemetation boto3

解决方案

dynamodb can force uniqueness only for hash-range table keys (and not for global secondary index keys)

in your case there are 2 options:

1) force it on application level - query for records, and find if duplicate

2) add another dynamodb table with hash/range values (that can enforce uniqeness), you can query this table before putting an item to the main table

3) use application locks (memcache..)

4) dont use dynamodb (maybe its not answer your requirements )

referring you to answers here:

DynamoDB avoid duplicate non-key attributes

DynamoDB consistent reads for Global Secondary Index

这篇关于如何使用ConditionExpression检查dynamodb中是否已经存在非键属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆