0

I have this DynamoDB table

TableName: MyTable 
    string HashKey: Id,  
    string RangeKey: createTime
Other attributes
    string partId
    string carNum
    string partId_carNum
Local_secondary_index : partId, projection_type       = "ALL"
Local_secondary_index : partId_carNum, projection_type  = "ALL"

I am trying to achieve post with unique combination of Id and partId_carNum. But the conditionExpression is not working. I am seeing duplicate entries in the table. What is wrong in my code?

Here is how my typeScript looks

Below is an example of an item

 {
   "Id" : "000001823841",
   "partId" : "1",
   "carNum" : "car",
   "createTime" : "124232353"
   }



 const params: PutItemInput = {
            TableName: MyTable,
            Item: item,
            ConditionExpression: 'Id <> :f AND partId_carNum <> :g',
            ExpressionAttributeValues: {
                ':f': { 'S': '000001823841' },
                ':g': { 'S': '1#car' }
            }
        };

 return await new DynamoDB()
            .putItem(params)
            .promise()
            .then(() => {
                console.log(`SUCCESS: Event with  ID inserted`);
            })
            .catch(err => {
                console.error(`FAILED to write event to ${params.TableName}. with Error: ${err}`);
            });

1 Answer 1

2

DynamoDB does not have a built-in mechanism for ensuring the uniqueness of attributes that are not the primary key.

According to the PutItem docs:

To prevent a new item from replacing an existing item, use a conditional expression that contains the attribute_not_exists function with the name of the attribute being used as the partition key for the table. Since every record must contain that attribute, the attribute_not_exists function will only succeed if no matching item exists

You have a few options here:

  1. Build partId_carNum into your primary key.
  2. Use transactions to simulate the unique constraints in your application code.

Option 2 may feel a bit hackey if you're coming from a RDBMS background, but it's a common pattern in DDB.

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.