我是第一次在本地玩具项目中直接使用Dynamo。我正在尝试创建一个由条件表达式保护的记录-如果用户名(范围键)或uniqueId(哈希键)已经存在,则失败:"attribute_not_exists(UserId) and attribute_not_exists(Username)"
。但是,当我使用相同的用户名放置记录时,不会出现冲突-扫描表即可确认这一点。我正在使用localstack(本地AWS模拟),如果有区别的话。
问题:
这是创建记录的逻辑:
userID := GenerateUniqueID()
record := UserCredentialsRecord{
UserID: userID,
Username: username,
Password: base64.StdEncoding.EncodeToString(hashedPassword),
Salt: base64.StdEncoding.EncodeToString(salt),
Email: email,
AccountCreatedTS: time.Now().Unix(),
}
...
input := &dynamodb.PutItemInput{
Item: av,
TableName: aws.String(userCredentialsTableName),
ConditionExpression: aws.String("attribute_not_exists(UserId) and attribute_not_exists(Username)"),
}
...
_, err = session.PutItem(input)
if err != nil {
fmt.Println("Got error calling PutItem:", err.Error())
}
这是localstack中的Dynamo表:localstack | ++ aws --endpoint-url=http://localstack:4566 dynamodb create-table --table-name UserCredentials --attribute-definitions AttributeName=UserID,AttributeType=S AttributeName=Username,AttributeType=S --key-schema AttributeName=UserID,KeyType=HASH AttributeName=Username,KeyType=RANGE --provisioned-throughput ReadCapacityUnits=1,WriteCapacityUnits=1
localstack | {
localstack | "TableDescription": {
localstack | "AttributeDefinitions": [
localstack | {
localstack | "AttributeName": "UserID",
localstack | "AttributeType": "S"
localstack | },
localstack | {
localstack | "AttributeName": "Username",
localstack | "AttributeType": "S"
localstack | }
localstack | ],
localstack | "TableName": "UserCredentials",
localstack | "KeySchema": [
localstack | {
localstack | "AttributeName": "UserID",
localstack | "KeyType": "HASH"
localstack | },
localstack | {
localstack | "AttributeName": "Username",
localstack | "KeyType": "RANGE"
localstack | }
localstack | ],
localstack | "TableStatus": "ACTIVE",
localstack | "CreationDateTime": 1610668286.312,
localstack | "ProvisionedThroughput": {
localstack | "LastIncreaseDateTime": 0.0,
localstack | "LastDecreaseDateTime": 0.0,
localstack | "NumberOfDecreasesToday": 0,
localstack | "ReadCapacityUnits": 1,
localstack | "WriteCapacityUnits": 1
localstack | },
localstack | "TableSizeBytes": 0,
localstack | "ItemCount": 0,
localstack | "TableArn": "arn:aws:dynamodb:us-east-1:000000000000:table/UserCredentials"
localstack | }
localstack | }
最佳答案
您对attribute_not_exists
条件表达式的作用有误解。
这并不意味着该属性在表中的任何项目上都不存在,而是在您正在使用的项目上不存在该属性。
这样,操作按设计进行。
如果要确保没有两个具有相同用户名或用户ID的项添加到表中,则必须使用这两个属性作为表的主键,或者想出另一种方法来检查重复。
关于go - 具有多个条件的Dynamo putItem在本地堆栈中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65728762/