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

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

问题描述

仅当userId,电子邮件和用户名不存在时,我才想插入到用户表中(希望它们是唯一的)。

userId是主键(哈希键,数据类型-Number)。

用户名和电子邮件是非关键属性(均为字符串)。

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

这是我尝试的方式:

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条件表达式

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

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

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 )

我正在使用Python实现 boto3

I am using Python implemetation boto3

推荐答案

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

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

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

in your case there are 2 options:

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

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

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

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)使用应用程序锁(内存缓存..)

3) use application locks (memcache..)

4)不要使用dynamodb(也许不是满足您的要求)

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

在这里引荐您回答:

DynamoDB避免重复的非关键属性

DynamoDB全球二级指数的读数一致

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

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