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

2024-04-18 20:36:36 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我有一个具有userId散列键和productId范围键的表,那么只有在使用boto3的dynamodb绑定还不存在的情况下,如何将项放入该表?

正常的放置物品的调用如下所示

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

我的带有条件表达式的调用如下所示:

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

但这每次都会引发条件检查失败异常。是否存在具有相同productId的项。


Tags: uidput表达式table情况boto3item条件
3条回答

不幸的是,这方面的文档并不是非常清楚。我需要做一些类似的事情,下面是对我有用的,使用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

与另一个答案类似,关键是属性不存在函数,但我最初不清楚如何让它起作用。经过一些实验,我能让它与上述。

您不需要sortkey(或range key),只要分区键或散列键就足够了。

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

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

来自boto3documentation

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.

我正在使用dynamodb2 overwrite parameteron item.save()

相关问题 更多 >