benhowdle89
benhowdle89

Reputation: 37464

DynamoDB - update/create item using Hash and Range key within TransactWrite

I have the following table:

"KeySchema": [
    {
      "AttributeName": "Value",
      "KeyType": "HASH"
    },
    {
      "AttributeName": "Id",
      "KeyType": "RANGE"
    }
]

What I'm trying to do is update a record, but if it doesn't exist, create it.

This did not work, because it seems you can't update the Range key? (the Id field won't change, but the Value will)

I read that the best thing to do is to delete the item, then re-create it. However, doing this leads to the error Transaction request cannot include multiple operations on one item.

Very simply, I'd like to go from this record:

  Item: {
     Value: 'Email|[email protected]',
     Id: '01E9AR3D4MQ3CDKE98SM8CR5Q3'
  }

to this (and if the Key of Id and Value doesn't exist, create it):

  Item: {
     Value: 'Email|[email protected]',
     Id: '01E9AR3D4MQ3CDKE98SM8CR5Q3'
  }

But it seems that I can't easily do this within this.db.transactWrite(req).promise()

Upvotes: 1

Views: 1497

Answers (2)

Derrops
Derrops

Reputation: 8117

Firstly don't you want your email to be your sort key? Your Ids look like a hash and don't have an order or am I missing something?

I think actually your are doing something wrong. An ID really should never be updated. Rather have a normal attribute email/age/etc and you can create an LSI on that if your partition key is unchanged, or GSI if you are needing to change your partition key, and then query that table.

You don't need to delete and recreate values to achieve this.

Upvotes: 0

NicoM
NicoM

Reputation: 135

I think you can use a PUTItem request, it will create a new row if missing or update it if already exists.

Just be aware to have all row data in the PUTItem request (in case you have other columns than HASH and RANGE), if not some data can be lost.

Note : PUTItem request can also be used in BatchWriteItem requests.

Some usefull links :

Hope this will help you.

Upvotes: 1

Related Questions