Python 如何使用 boto3 有条件地将项目插入到 dynamodb 表中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37053595/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 18:44:52  来源:igfitidea点击:

How do I conditionally insert an item into a dynamodb table using boto3

pythonamazon-dynamodbboto3

提问by aychedee

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?

如果我有一个带有 userId 哈希键和 productId 范围键的表,只有当它不存在使用 boto3 的 dynamodb 绑定时,我该如何将它放入该表中?

The normal call to put_item looks like this

对 put_item 的正常调用如下所示

table.put_item(Item={'userId': 1, 'productId': 2})

My call with a ConditionExpression looks like this:

我对 ConditionExpression 的调用如下所示:

table.put_item(
    Item={'userId': 1, 'productId': 2}, 
    ConditionExpression='userId <> :uid AND productId <> :pid', 
    ExpressionAttributeValues={':uid': 1, ':pid': 3}
)

But this raises a ConditionalCheckFailedException every time. Whether an item exists with the same productId or not.

但这每次都会引发 ConditionalCheckFailedException。是否存在具有相同 productId 的项目。

回答by jimjkelly

The documentation for this unfortunately isn't super clear. I needed to accomplish something similar, and here's what worked for me, using boto3:

不幸的是,这方面的文档不是很清楚。我需要完成类似的事情,这对我有用,使用 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

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.

与其他答案类似,关键在 attribute_not_exists 函数中,但我最初不清楚如何让它工作。经过一些实验,我能够按照上述方法进行操作。

回答by Venkat.V.S

You dont need the sortkey( or range key) just the partition key or hash key is enough.

您不需要排序键(或范围键),只需分区键或散列键就足够了。

try:
    table.put_item(
        Item={
            'foo':1,
            'bar':2,
        },
        ConditionExpression='attribute_not_exists(foo)'
    )
except botocore.exceptions.ClientError as e:
    # Ignore the ConditionalCheckFailedException, bubble up
    # other exceptions.
    if e.response['Error']['Code'] != 'ConditionalCheckFailedException':
        raise

回答by Eyal Ch

i think that you will get better documentation using client.put_item rather than table.put_item

我认为您会使用 client.put_item 而不是 table.put_item 获得更好的文档

from boto3 documentation:

来自 boto3文档

To prevent a new item from replacing an existing item, use a conditional expression that contains the attribute_not_exists function with the name of the attribute being used as the partition key for the table. Since every record must contain that attribute, the attribute_not_exists function will only succeed if no matching item exists.

要防止新项目替换现有项目,请使用包含 attribute_not_exists 函数的条件表达式,该函数的名称用作表的分区键。由于每条记录都必须包含该属性,因此 attribute_not_exists 函数仅在不存在匹配项时才会成功。

ConditionExpression:

条件表达式:

ConditionExpression (string) -- A condition that must be satisfied in order for a conditional PutItem operation to succeed.

An expression can contain any of the following:

Functions: attribute_exists | attribute_not_exists | attribute_type | contains | begins_with | size These function names are case-sensitive.

ConditionExpression(字符串)——一个必须满足的条件,条件 PutItem 操作才能成功。

表达式可以包含以下任何内容:

函数:attribute_exists | 属性不存在 | 属性类型 | 包含 | 开始于 | size 这些函数名称区分大小写。

i am using dynamodb2 overwrite parameteron item.save()

我使用dynamodb2覆盖参数item.save()