Database Reference
In-Depth Information
Conditional writes
We know that the putItem request first searches for the records with given keys; if it
finds any matching record, then it replaces the record with a new value. If it does not find
any matching record, it simply inserts it as a new record. This can be dangerous and may
lead to unwanted record update. So to avoid this, you can perform conditional writes on
items, in which you pass on a flag that first checks whether the value is already present; if
yes, then do not add anything, and if not present, then only add a new value.
Android
Here is how we use conditional writes using the AWS SDK for Android:
// Create map for expected attribute value
Map<String,ExpectedAttributeValue> expectedAttri = new
HashMap<String,ExpectedAttributeValue>();
//set attribute whose value you need to check
expectedAttri.put("recordId", new
ExpectedAttributeValue().withExists(false));
// set the same in request
putItemRequest.setExpected(expectedAttri);
We can also use ExpectedAttributeValue to implement a counter. An atomic
counter means that you want the value to be updated correctly and to always reflect the ex-
act value. For example, in our Product table, if we have an attribute, say, number of
items in stock, this attribute always needs to be in the exact state, so we can create an atom-
ic counter using ExpectedAttributeValue as shown in the following code:
// Create a request which updates the no. of items in stock
Map<String,AttributeValue> item = new HashMap<String,
AttributeValue>();
item.put("productId", new AttributeValue().withN("777"));
item.put("recordId", new
AttributeValue().withS("NoOfItemsInStock"));
item.put("data", new AttributeValue().withS("3"));
PutItemRequest putItemRequest = new
Search WWH ::




Custom Search