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
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.