Home > Software design >  How to enforce GSI uniqueness on a PutItemRequest
How to enforce GSI uniqueness on a PutItemRequest

Time:10-29

I am attempting to use a PutItemRequest to insert records into a DynamoDB table, however I do not want the insert to succeed when certain values on the inserted item already exist on other items.

Here is the code for the request:

var req = PutItemRequest.builder()
            .tableName(TABLE_NAME)
            .item(getAllValues(settings))
            .conditionExpression("attribute_not_exists(#"   MAC_ADDRESS   ") AND attribute_not_exists(#"   REGISTRATION_CODE   ")")
            .expressionAttributeNames(Map.of("#"   MAC_ADDRESS, MAC_ADDRESS, "#"   REGISTRATION_CODE, REGISTRATION_CODE))
            .build();

The table already contains an item with a mac address of '000000000000' so I would expect the above to fail when trying to insert another item with the same mac address, but the insert succeeds.

What am I doing wrong here? Both MAC_ADDRESS and REGISTRATION_CODE are GSI's.

CodePudding user response:

Unlike the actual DDB table, GSI's and LSI's always allow duplicates.

What are you using as a primary key (hash & sort) for the table itself?

If you want to DDB enforce uniqueness, you'll need to come up with a way to use the unique attributes in the table's primary key.

CodePudding user response:

The only way to make this possible introduces a lot of overhead which perhaps is not the best solution for your use-case.

https://aws.amazon.com/blogs/database/simulating-amazon-dynamodb-unique-constraints-using-transactions/

I would suggest that you rethink your tables schema to allow the base table handle the uniqueness and have the indexes based on other attributes.

  • Related