如何使用 boto3 有条件地将项目插入 dynamodb table

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

如果我有一个 table,其散列键为 userId,范围键为 productId 我如何将一个项目放入 table 只有当它不存在时才使用 boto3 的 dynamodb绑定?

对 put_item 的正常调用如下所示

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

我使用 ConditionExpression 的调用如下所示:

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

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

我认为使用 client.put_item 而不是 table.put_item

可以获得更好的文档

来自 boto3 documentation:

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.

条件表达式:

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.

我在 item.save()

上使用 dynamodb2 overwrite parameter

不幸的是,这方面的文档不是很清楚。我需要完成类似的事情,这对我有用,使用 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 函数,但我最初并不清楚如何让它发挥作用。经过一些实验,我能够按照上面的方法进行操作。

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

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