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

attribute_not_exists dynamodb python
dynamodb putitem
dynamodb put item if not exists javascript
dynamodb check if item exists
dynamodb put if not exists python
dynamodb put if not exists nodejs
dynamodb update-item
dynamodb update if

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 that the hash is unique (ignoring the range). Other times I want to allow duplicate hashes, but guarantee that the hash and range combination is unique. How can I accomplish this?

I experimented with attribute_not_exists. It seems to handle the second case, where it checks the hash + key combination. Here's a PHP sample:

$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(hash)'
));

Oddly, it doesn't seem to matter if I use attribute_not_exists(hash) or attribute_not_exists(range). They both seem to do exactly the same thing. Is this how it's supposed to work?

Any idea how to handle the case where I only want to check hash for uniqueness?


DynamoDB - Put item if hash (or hash and range , DynamoDB - Put item if hash (or hash and range combination) doesn't exist - oddly, doesn't seem matter if use attribute_not_exists(hash) or  DynamoDB uses the partition key's value as input to an internal hash function. The output from the hash function determines the partition (physical storage internal to DynamoDB) in which the item will be stored.


This version of explanation taken from amazon aws forum says that a search will look an item that matches a provided hash key and then only checks if the attribute exists in that record. It should works the same if you have a hash and a range keys, I suppose.

If a request try to find an existing item with hash key "b825501b-60d3-4e53-b737-02645d27c2ae". If this is first time this id is being used there will be no existing item and "attribute_not_exists(email)" will evaluate to true, Put request will go through.

If this id is already used there will be an existing item. Then condition expression will look for an existing email attribute in the existing item, if there is an email attribute the Put request will fail, if there is no email attribute the Put request will go through.

Either way it's not comparing the value of "email" attribute and it's not checking if other items in the table used the same "email" value.

If email was the hash key, then request will try to find an existing item with hash key "tielur@example.me".

If there is another item with same email value an existing item will be found. Since email is the hash key it has to be present in the existing item and "attribute_not_exists(email)" will evaluate to false and Put request will fail.

If "email" value is not used before existing item will not be found and "attribute_not_exists(email)" will evaluate to true hence Put request will go through.

Core Components of Amazon DynamoDB, You'll discover the basics of tables, items, attributes, and how they work together to An attribute is a fundamental data element, something that does not need to be The combination of Artist and SongTitle distinguishes each item in the table DynamoDB uses the partition key's value as input to an internal hash function. This is the same as the partition key value of the item itself. SizeEstimateRangeGB - An estimate of item collection size, in gigabytes. This value is a two-element array containing a lower bound and an upper bound for the estimate. The estimate includes the size of all the items in the table,


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')
));

Amazon DynamoDB - AWS Mobile SDK, In contrast, DynamoDB only requires that a table has a primary key, but does Hash and Range Key: The primary key is made of two attributes. Each item in the table is uniquely identified by the combination of its hash and range key values. get, put, query, scan, and update items in a specific DynamoDB table, which is  The HASH and RANGE keys allow for a one-to-many like structure -- for a single HASH key, there can be multiple RANGE keys. When thinking about how to set up our data structure, think how you would fill in the blanks for the following query: "Give me all of the ____ from a particular ___." The element you put in the first blank should be your


Following Jun711's answer, here is what I did to implement putItem only if hash doesn't exist in Kotlin. DocId is the hash key of my DynamoDB table.

val item = Item().withPrimaryKey(...).withString(...)
val putItemSpec = PutItemSpec().withItem(item)
                    .withConditionExpression("attribute_not_exists(DocId)")
table.putItem(putItemSpec)

If using DynamoDBMapper annotations, here is an example.

@DynamoDBTable(tableName = "Docs")
class Docs {
    // Partition key
    @get:DynamoDBHashKey(attributeName = "DocId")
    var docId: String? = null
}

val doc = Docs().apply {
    docId = "myId"
}

val mapper = DynamoDBMapper(AmazonDynamoDBClientBuilder.defaultClient())

// As suggested by http://rrevo.github.io/2018/03/09/dynamo-no-update/
val ifDocIdNotExists = DynamoDBSaveExpression().apply {
    expected = mapOf("DocId" to ExpectedAttributeValue().apply {
        isExists = false
    })
}

mapper.save(doc, ifDocIdNotExists)

Catch com.amazonaws.services.dynamodbv2.model.ConditionalCheckFailedException to handle the case where the hash key already exists.

Core concepts of Amazon DynamoDB - Tensult Blogs, DynamoDB organises data as tables and each table contains several items (rows​) and is also called as the partition key and some times is also referred as a Hash Key. Primary key is just a combination of both Partition key and Sort Key. BatchWriteItem: This can be used to delete or put items on one or more tables in  To determine the item to get, in this example, the GetItem method uses the hash-and-range primary key of the target item. To determine the table to get the item from, the Table class’s LoadTable method uses an instance of the AmazonDynamoDBClient class and the name of the target table in DynamoDB.


You can use AND operation if your table has hash and range

'ConditionExpression' => 'attribute_not_exists(hash) AND attribute_not_exists(range)'

Is it possible to insert an item only if the hash+range key does not , Is it possible to insert an item only if the hash+range key does not already exist? an item that doesn't exist in a transaction (either with an Put/Update/Delete or More details are here: https://github.com/awslabs/dynamodb-  The AWS Command Line Interface (AWS CLI) provides support for all of the AWS database services, including Amazon DynamoDB. You can use the AWS CLI for ad hoc operations, such as creating a table. You can also use it to embed DynamoDB operations within utility scripts. To list the AWS CLI commands for DynamoDB, use the following command.


DynamoDB, When designing your application, keep in mind that DynamoDB does not The individual PutItem and DeleteItem operations specified in BatchWriteItem are Your request contains at least two items with identical hash and range keys However, the combination of the following three elements is guaranteed to be unique:. When you refer to an item that doesn't exist in a transaction (either with an Put/Update/Delete or with a Get), a new "transient" item is insert and marked as such while the transaction is happening, and locked. If the transaction is rolled back, that "transient" item is deleted. So in your "read then write" use case, it would look like this:


DynamoDB Cookbook, Here, if you want to fetch an item/s whose id is 1, put 1 in the textbox against the We can also query data by providing a combination of Hash Key and Range  The single most important part of using DynamoDB begins before you ever put data into it: designing the table(s) and keys. Keys (Amazon calls them primary keys) can be composed of one attribute, called a hash key, or a compound key called the hash and range key. The key is used to uniquely identify an item in a table.


DynamoDB Cheatsheet – Everything you need to know about , A Partition is when DynamoDB slices your table up into smaller chunks Partition Key (PK) is also known as HASH; The Sort Key (SK) is also known as RANGE When creating a Composite Primary Key the combined PK and SK must aws dynamodb put-item Creates a new item, or replaces an old item  Amazon DynamoDB is a fully managed proprietary NoSQL database service that supports key-value and document data structures and is offered by Amazon.com as part of the Amazon Web Services portfolio. DynamoDB exposes a similar data model to and derives its name from Dynamo , but has a different underlying implementation.