DynamoDB - Put item if hash (or hash and range combination) doesn't exist

后端 未结 6 1158
误落风尘
误落风尘 2020-12-05 00:32

Here are my use cases: I have a Dynamo table with a hash + range key. When I put new items in the table, I want to do a uniqueness check. Sometimes I want to guarantee th

6条回答
  •  -上瘾入骨i
    2020-12-05 00:47

    Careful with reserved keywords.
    attribute_not_exists will not work as expected if the provided attributeName matches a word from the reserved list. hash and range are both reserved and thus require the need to work around that issue by using ExpressionAttributeNames.

    The following example allows for duplicate partition keys and only fails if there's already an Item in the Table with the provided partition AND sort key.

    $client->putItem(array(
        'TableName' => 'test',
        'Item' => array(
            'hash' => array('S' => 'abcdefg'),
            'range' => array('S' => 'some other value'),
            'whatever' => array('N' => 233)
        ),
        'ConditionExpression' => 'attribute_not_exists(#h) AND attribute_not_exists(#r)',
        'ExpressionAttributeNames' => array('#h' => 'hash', '#r' => 'range')
    ));
    

    And this one would make sure the partition key named hash is unique.

     $client->putItem(
         'TableName' => 'test',
         'Item' => array(
            'hash' => array('S' => 'abcdefg'),
            'range' => array('S' => 'some other value'),
            'whatever' => array('N' => 233)
        ),
        'ConditionExpression' => 'attribute_not_exists(#h)',
        'ExpressionAttributeNames' => array('#h' => 'hash')
    ));
    

提交回复
热议问题