问题描述
如果我有一个表,其中的哈希键为userId,范围键为productId,那么仅当使用boto3的dynamodb绑定不存在该项目时,才将其放入该表中吗?
If I have a table with a hash key of userId and a range key of productId how do I put an item into that table only if it doesn't already exist using boto3's dynamodb bindings?
对put_item的正常调用如下所示:
The normal call to put_item looks like this
table.put_item(Item={'userId': 1, 'productId': 2})
使用ConditionExpression进行的呼叫如下:
My call with a ConditionExpression looks like this:
table.put_item(
Item={'userId': 1, 'productId': 2},
ConditionExpression='userId <> :uid AND productId <> :pid',
ExpressionAttributeValues={':uid': 1, ':pid': 3}
)
但这每次都会引发ConditionalCheckFailedException。是否存在具有相同productId的商品。
But this raises a ConditionalCheckFailedException every time. Whether an item exists with the same productId or not.
推荐答案
不幸的是,有关此文件的文档并不十分清楚。我需要使用boto3完成类似的操作,这对我有用:
The documentation for this unfortunately isn't super clear. I needed to accomplish something similar, and here's what worked for me, using boto3:
try:
table.put_item(
Item={
'foo':1,
'bar':2,
},
ConditionExpression='attribute_not_exists(foo) AND attribute_not_exists(bar)'
)
except botocore.exceptions.ClientError as e:
# Ignore the ConditionalCheckFailedException, bubble up
# other exceptions.
if e.response['Error']['Code'] != 'ConditionalCheckFailedException':
raise
类似于其他答案,关键是在attribute_not_exists函数中,但是最初我不清楚如何使它起作用。经过一番试验,我得以将其与上述方法结合使用。
Similar to the other answer, the key is in the attribute_not_exists function, but it was unclear to me initially how to get that to work. After some experimentation, I was able to get it going with the above.
这篇关于如何使用boto3有条件地将项目插入到dynamodb表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!