![](/img/trans.png)
[英]DynamoDB: KeyConditionExpression to check if an attribute exists or not null
[英]how to check if non-key attribute already exists in dynamodb using ConditionExpression?
我想僅在userId,email和username不存在時插入到users表中(希望這些是唯一的)。
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條件表達式
但即使用戶名或電子郵件已經存在於db中,它也會每次都插入到表中。
(我給新的userIdNext,因為它是主鍵,不能重復)
我正在使用Python實現boto3
dynamodb只能對哈希范圍表鍵強制唯一性(而不是全局二級索引鍵)
在您的情況下有2個選項:
1)強制它在應用程序級別 - 查詢記錄,並查找是否重復
2)添加另一個帶有散列/范圍值的dynamodb表(可強制執行uniqeness),您可以在將項目放入主表之前查詢此表
3)使用應用程序鎖(memcache ..)
4)不要使用dynamodb(也許它不能滿足你的要求)
在這里向您推薦答案:
好的,我在申請中發現了這個錯誤。
我嘗試對DynamoDB執行條件put項,但是我傳遞了一個不同的主鍵,即DynamoDB上存在的主鍵,此時將創建一個新對象並忽略條件表達式。
# id primary key
id = 123
# email is only index
email = "email@email.com"
item = {
"id": id,
"email": email
"info": {
"gender": "male",
"country": "Portugal"
}
}
response = self._table.put_item(Item=item, ConditionExpression="email <> :v_email", ExpressionAttributeValues={":v_email": email})
如果您希望條件表達式在DynamoDB put_item上正常工作,您應該發送與DB上存在的主鍵相同的主鍵。
kishorer747,你能把你的代碼樣本做到這一點嗎? “我有全局二級索引來檢查用戶名或電子郵件是否已存在,但它不是原子的。所以,如果2個用戶同時查詢並獲得該email1,則它們都會插入到用戶表中。如果沒有檢查到驗證電子郵件/用戶名是否已經存在,我們有重復的電子郵件/用戶名條目“
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.