开发者

SimpleDB: Insert item only if it doesn't already exist

开发者 https://www.devze.com 2023-02-10 11:06 出处:网络
I\'d like to add a new item to a Amazon SimpleDB domain only if there isn\'t already another item with the same item name.

I'd like to add a new item to a Amazon SimpleDB domain only if there isn't already another item with the same item name.

I know how to do it for an attribute. But I want the item name to be checked to make sure it's unique and it won't overwrite an existing item – without an additional select query, of course.

Example for checking an attribute:

https://sdb.amazonaws.com/
?Action=PutAttributes
&DomainName=MyDomain
&ItemName=JumboFez
&Attribute.1.Name=quantity
&Attribute.1.Value=14
&Attribute.1.Replace=true
&Expected.1.Name=quantity
&Expected.1.Exists=false
&AWSAccessKeyId=[valid access key id]
[...]

According to the FAQ this should be possible:

“These semantics can also be used to implement functionality such as counters, inserting an item only if it does not already exist […]”

开发者_Python百科


You are correct, you can use conditional put to achieve this SimpleDB Docs conditional puts.

Essentially any attribute on the item you know you will have can be used with an existence check on the conditional update to ensure that the put only happens if the attribute does not exist for that particular itemName.

In java using amazon's java SDK this would look something like :-

// add a conditional check to ensure that the specified profile does not already
// exist - if there's a timestamp, then this profile already exists
UpdateCondition condition = new UpdateCondition("quantity", null, false);

final PutAttributesRequest request = new PutAttributesRequest().withDomainName("MyDomain");
request.setItemName("JumboFez");
request.setAttributes(attributes);
request.setExpected(condition);

sdb.putAttributes (request);

Which essentially reduces down to what you have written and will do what you want as long as you never have a valid item which has no 'quantity' attribute.

Possibly worth noting is that in your example you have replace set to true, and if you are using conditional puts to ensure the item is a new item, you shouldn't need to set replace=true (according to the docs and empirical evidence, replace=true costs more than replace=false and takes longer).


You can generate the item name based on the current timestamp. And use like % method to fetch the result.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号