Search code examples
amazon-dynamodbdynamodb-queries

Can we update DynamoDB GSI partition key?


According to the docs, I understand PrimaryKey PK & SortKey SK can't be updated on the main table. However this is not clear for GlobalSecondaryIndex (GSI) and it seems to be ok to update GSI SK (correct me if I'm wrong).

Suppose I had the following account table, where we have the following PK (ID) + SK (createdAt)

id     createdAt     email          username
21     20220101      abc@xyz.com    blah1
22     20220102      123@xyz.com    blah2
...

If I wanted to index by email, I could create a GSI where email is PK and createdAt is SK.

How could we handle a scenario where we allowed a user to change their email or username?

  • Is this essentially a new PrimaryKey in another partition, hence a new row in the GSI table?
  • Will this mean the old row may be stale in the GSI? If so, does DynamoDB clean up the old entry if we can't delete directly at the GSI?

Solution

  • GSIs don't accept writes directly, but you can update the keys of a GSI item by editing the item in the base table.

    Note there's a potential "write amplification" when you do this because one write to the base table results in two writes to the GSI: a delete under the old key and an insert under the new key. This is all done for you automatically.