Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DynamoDb with ConditionExpression

Consider the following DynamoDb table:

TableName: foo-bar HashKey: Foo, str RangeKey: Bar, str Name: Baz, str

Now with the vogels API I'm trying to insert an item with a HashKey, a new RangeKey, and a Name.

But the Name must not exist for the given HashKey:

So we define the table layout for the vogels API:

var foobar = vogels.define("foo-bar", {
    tableName: "foo-bar",
    hashKey: "foo",
    rangeKey: "bar",
    schema: {
        "foo": Joi.string(),
        "bar": Joi.string(),
        "name": Joi.string()
    }
});

And then the insertion of the item:

var itemToInsert = { foo: "foo", bar: "bar2", name: "TEST" };

var params = {};
params.ConditionExpression = "foo <> :foo AND name <> :name";
params.ExpressionAttributeValues = {
    ":foo": itemToInsert.foo,
    ":name": itemToInsert.name
};

foobar
    .create(itemToInsert, params, function(error, data) {
        if(error) {
            console.log(error);
        }
        else {
            console.log(data);
        }
});

There is already an item in the table with the following values: {foo: "foo", bar: "bar", name: "TEST" }

So I'm expecting the system to give me an error since there is already a match because of the ConditionExpression, however the item is inserted without a problem. Is this not possible with DynamoDb?

Notice that it doesn't matter whether I use vogels or directly the aws-sdk, both of them have the same problem, i.e. the item is inserted and the ConditionExpression doesn't block the insert.

like image 402
Snake Avatar asked Mar 17 '23 21:03

Snake


1 Answers

The reason DynamoDB is inserting your item is because your table is using a compound key of hashkey: foo, rangekey: bar. You are attempting to insert an item with a different key, in this case hashkey: foo, rangekey: bar2. In DynamoDB, when inserting an item the condition expressions are only tested against an existing item matching exactly the same hash and range keys.

You are attempting to add a unique constraint on a non-key attribute, this is not currently possibly with DynamoDB and will require a schema change in order to enforce this constraint.

like image 159
Ryan Fitzgerald Avatar answered Mar 23 '23 09:03

Ryan Fitzgerald