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

后端 未结 3 692
無奈伤痛
無奈伤痛 2020-12-25 12:18

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 bindi

3条回答
  •  悲&欢浪女
    2020-12-25 13:07

    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
    

提交回复
热议问题