DynamoDB, Check if Parent Exist before insert ,condition expression

Viewed 27

I have a single table design in AWS Dynamodb something like below with two GSI's

PK SK
USER#Alex USER#Alex
ORDER#1
ORDER#2

So now if I do an insert item. With condition expression ensuring that User exist before adding an order. How do I go about checking attribute exist?

I try below and it fails. I know why after reading the article.

const putItemParams = {
  TableName: process.env.TABLE_NAME,
  Item: {
    PK: {
      S: "USER#Alex",
    },
    SK: {
      S: "ORDER#1",
    },
    ConditionExpression: "attribute_exists(PK)",
  },
};

After reading this article by @AlexDebrie https://www.alexdebrie.com/posts/dynamodb-condition-expressions/

I understand that Dynamodb looks for the Put Item key of the Item that is going to be written and checks if PK exists which in the above statement will be wrong. How do I fit in the logic.

I can think of transact items

transactWriteItems : [
  ConditionCheck : checkIf user exist with Pk:USER#Alex and SK:USER#Alex,
  Put :  Then do the put
]

I am not sure if I am missing something obvious. If transactWriteItems is the only way then obvious disadvantage is that for my many put Items will turn into transactWriteItems with associated cost doubling since TransactWriteItems has double the RRU and WRU.

1 Answers

Why not just do a (low cost) get-item to check if the user exists and if it does then do the order insert and if it doesn’t then do whatever appropriate?

This doesn’t seem like it has to be transactional.

Are you worried another process might delete the user while this one is trying to insert the order? Seems a weird design if so.

Related