1

I have a dynamodb table in which columns are url and organization_name url is the primary key. How can I check if a url is already present in the table when I try to update the table with new data. I am using python boto3 for updating the table.

I used the below code for checking

       trans = {}
       trans['url'] = URL
       trans['html_data'] = data
       trans['organization_name'] = org_name
       try:
            table.put_item(Item=trans,ConditionExpression='attribute_not_exists(url)')
       except:
            mesg = 'Data Insertion Not Successfull'
       mesg = 'Data Saved Successfully'

Is this the correct way for writing data to the table if url is not present.

1 Answer 1

1

This is what condition expressions are for!

Here's how this would look using the NodeJS API:

const ddb = new AWS.DynamoDB()

ddb.putItem({
  TableName: "...",
  Item: {
    url: {S: "https://stackoverflow.com"},
    organization_name: {S: "my org"},
    other_stuff: {S: "...stuff"}
  },
  ConditionExpression: "attribute_not_exists(url)"
})

This put statement will fail if url exists, i.e. it will only work if an item with that url does not already exist in that table. And puts are always consistent (write is not reported OK until consensus is reached from storage nodes).

Full documentation here: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.ConditionExpressions.html

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.