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

后端 未结 6 1170
误落风尘
误落风尘 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条回答
  •  广开言路
    2020-12-05 01:02

    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.

提交回复
热议问题