ayc*_*dee 21 python amazon-dynamodb boto3
如果我有一个带有userId的散列键和productId的范围键的表,那么只有在使用boto3的dynamodb绑定不存在的情况下,如何才能将该项放入该表中?
对put_item的正常调用如下所示
table.put_item(Item={'userId': 1, 'productId': 2})
Run Code Online (Sandbox Code Playgroud)
我使用ConditionExpression的调用如下所示:
table.put_item(
    Item={'userId': 1, 'productId': 2}, 
    ConditionExpression='userId <> :uid AND productId <> :pid', 
    ExpressionAttributeValues={':uid': 1, ':pid': 3}
)
Run Code Online (Sandbox Code Playgroud)
但是每次都会引发ConditionalCheckFailedException.项目是否存在具有相同productId的项目.
jim*_*lly 55
遗憾的是,这方面的文件并不是很清楚.我需要完成类似的事情,这对我有用,使用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
Run Code Online (Sandbox Code Playgroud)
与其他答案类似,关键在于attribute_not_exists函数,但最初我不清楚如何使其工作.经过一些实验,我能够顺利完成上述工作.
您只需要分区键或哈希键就不需要sortkey(或range键)。
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
Run Code Online (Sandbox Code Playgroud)