gpt4 book ai didi

amazon-web-services - 仅当项目不存在时,如何在 dynamodb 中放置项目

转载 作者:行者123 更新时间:2023-12-04 15:41:02 30 4
gpt4 key购买 nike

我在 dynamodb 中有一个表,它只有一个分区键,只有当数据库中没有另一个具有相同分区键的项目时,我才想将一个项目放入数据库中。

我试过使用 ConditionExpression attribute_not_exists 无济于事。

问题是数据库中可能不存在某个项目,因此 attribute_not_exists 失败并显示
无效的条件表达式:运算符或函数需要文档路径;运算符或函数:attribute_not_exists

编辑:
您能否发布您使用的完整条件表达式+表分区键的名称? ——

Key: {
username: event.pathParameters.username
},
ExpressionAttributeValues: {
":username": event.pathParameters.username
},
Item: {
userId: event.requestContext.identity.cognitoIdentityId
},
ConditionExpression: "attribute_not_exists(:username)"

最佳答案

我刚刚用 attributes_not_exists 试过了条件,它似乎按预期工作:

$ aws create-table --table-name example1 \
--attribute-definitions AttributeName=pk,AttributeType=S \
--key-schema AttributeName=pk,KeyType=HASH --billing-mode PAY_PER_REQUEST
...
$ aws dynamodb put-item --table-name example1 \
--item '{"pk": {"S": "abc"}, "city": {"S": "NYC"}}'
$ aws scan --table-name example1
{
"Items": [
{
"city": {
"S": "NYC"
},
"pk": {
"S": "abc"
}
}
],
"Count": 1,
"ScannedCount": 1,
"ConsumedCapacity": null
}

$ aws dynamodb put-item --table-name example1 \
--item '{"pk": {"S": "abc"}, "city": {"S": "SF"}}' \
--condition-expression "attribute_not_exists(pk)"

An error occurred (ConditionalCheckFailedException) ...

$

为什么你的请求失败了?

根据您发布的请求,我相信罪魁祸首是您的条件表达式。

而不是 "attribute_not_exists(:username)"应该是 attribute_not_exists(username) . :前缀表示值占位符,而 attribute_not_exists函数不需要值,它需要一个属性名称。进行更改后,您还需要删除 ExpressionAttributeValues字段,因为它定义的值占位符(即: :username )不再在请求中的任何地方使用。

所以,总而言之,这个请求应该适合你:
Key: {
username: event.pathParameters.username
},
Item: {
userId: event.requestContext.identity.cognitoIdentityId
},
ConditionExpression: "attribute_not_exists(username)"

最后一个( super 小)评论:您发布的请求看起来像 update request .我相信对于您的用例,您可以使用 put这需要一个稍微简单的请求。具体来说,在 put您只需指定整个项目,无需与其他属性分开指定键。注意,就像 update , put还支持 ConditionExpression这是解决方案中的关键部分。

关于amazon-web-services - 仅当项目不存在时,如何在 dynamodb 中放置项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57783485/

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