下面列出了怎么用com.amazonaws.services.dynamodbv2.model.UpdateItemRequest的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void testCreateEntryAlreadyExists() throws Exception {
RawSecretEntry rawSecretEntry = constructRawEntry(SECRET_NAME);
UpdateItemRequest expectedUpdateRequest = constructUpdateItemRequest(rawSecretEntry, false, Optional.empty());
// Already exists will cause a check failed exception.
when(mockDynamoDBClient.updateItem(expectedUpdateRequest)).thenThrow(
new ConditionalCheckFailedException(""));
boolean exceptionThrown = false;
try {
dynamoDB.create(rawSecretEntry);
} catch (AlreadyExistsException e) {
assertEquals(e.getMessage(), "DynamoDB store entry already exists:{1={S: secret1,}, 2={N: 1,}}");
exceptionThrown = true;
}
assertTrue(exceptionThrown);
verify(mockDynamoDBClient, times(1)).updateItem(expectedUpdateRequest);
}
@Test
public void testUpdateEntryDoesNotExist() throws Exception {
RawSecretEntry rawSecretEntry = constructRawEntry(SECRET_NAME);
RawSecretEntry alternativeRawSecretEntry = constructAlternativeRawSecretEntry(SECRET_NAME);
UpdateItemRequest expectedUpdateRequest = constructUpdateItemRequest(rawSecretEntry, true, Optional.of(alternativeRawSecretEntry));
when(mockDynamoDBClient.updateItem(expectedUpdateRequest)).thenThrow(
new ConditionalCheckFailedException(""));
boolean exceptionThrown = false;
try {
dynamoDB.update(rawSecretEntry, alternativeRawSecretEntry);
} catch (DoesNotExistException e) {
assertEquals(e.getMessage(), "Precondition to update entry in DynamoDB failed:{1={S: secret1,}, 2={N: 1,}}");
exceptionThrown = true;
}
assertTrue(exceptionThrown);
// Check all the expected calls to AWS were made.
verify(mockDynamoDBClient, times(1)).updateItem(expectedUpdateRequest);
}
private static void updateAddNewAttribute() {
try {
HashMap<String, AttributeValue> key = new HashMap<String, AttributeValue>();
key.put("Id", new AttributeValue().withN("121"));
Map<String, AttributeValue> expressionAttributeValues = new HashMap<String, AttributeValue>();
expressionAttributeValues.put(":val1", new AttributeValue().withS("Some value"));
ReturnValue returnValues = ReturnValue.ALL_NEW;
UpdateItemRequest updateItemRequest = new UpdateItemRequest().withTableName(tableName).withKey(key)
.withUpdateExpression("set NewAttribute = :val1")
.withExpressionAttributeValues(expressionAttributeValues).withReturnValues(returnValues);
UpdateItemResult result = client.updateItem(updateItemRequest);
// Check the response.
System.out.println("Printing item after adding new attribute...");
printItem(result.getAttributes());
}
catch (AmazonServiceException ase) {
System.err.println("Failed to add new attribute in " + tableName);
System.err.println(ase.getMessage());
}
}
UpdateItemResult updateItem(final UpdateItemRequest request) throws BackendException {
setUserAgent(request);
UpdateItemResult result;
final int bytes;
if (request.getUpdateExpression() != null) {
bytes = calculateExpressionBasedUpdateSize(request);
} else {
bytes = calculateItemUpdateSizeInBytes(request.getAttributeUpdates());
}
getBytesHistogram(UPDATE_ITEM, request.getTableName()).update(bytes);
final int wcu = computeWcu(bytes);
timedWriteThrottle(UPDATE_ITEM, request.getTableName(), wcu);
final Timer.Context apiTimerContext = getTimerContext(UPDATE_ITEM, request.getTableName());
try {
result = client.updateItem(request);
} catch (Exception e) {
throw processDynamoDbApiException(e, UPDATE_ITEM, request.getTableName());
} finally {
apiTimerContext.stop();
}
meterConsumedCapacity(UPDATE_ITEM, result.getConsumedCapacity());
return result;
}
public static void updateItem(AmazonDynamoDBClient client, String tableName, String id, String val) {
java.util.Map<String, AttributeValue> key = new HashMap<String, AttributeValue>();
key.put("Id", new AttributeValue().withN(id));
Map<String, AttributeValueUpdate> attributeUpdates = new HashMap<String, AttributeValueUpdate>();
AttributeValueUpdate update = new AttributeValueUpdate()
.withAction(AttributeAction.PUT)
.withValue(new AttributeValue().withS(val));
attributeUpdates.put("attribute-2", update);
UpdateItemRequest updateItemRequest = new UpdateItemRequest()
.withTableName(tableName)
.withKey(key)
.withAttributeUpdates(attributeUpdates);
client.updateItem(updateItemRequest);
}
public UpdatePointResult updatePoint(UpdatePointRequest updatePointRequest) {
long geohash = S2Manager.generateGeohash(updatePointRequest.getGeoPoint());
long hashKey = S2Manager.generateHashKey(geohash, config.getHashKeyLength());
UpdateItemRequest updateItemRequest = updatePointRequest.getUpdateItemRequest();
updateItemRequest.setTableName(config.getTableName());
AttributeValue hashKeyValue = new AttributeValue().withN(String.valueOf(hashKey));
updateItemRequest.getKey().put(config.getHashKeyAttributeName(), hashKeyValue);
updateItemRequest.getKey().put(config.getRangeKeyAttributeName(), updatePointRequest.getRangeKeyValue());
// Geohash and geoJson cannot be updated.
updateItemRequest.getAttributeUpdates().remove(config.getGeohashAttributeName());
updateItemRequest.getAttributeUpdates().remove(config.getGeoJsonAttributeName());
UpdateItemResult updateItemResult = config.getDynamoDBClient().updateItem(updateItemRequest);
UpdatePointResult updatePointResult = new UpdatePointResult(updateItemResult);
return updatePointResult;
}
@Test
public void getThenUpdateNewItem() {
Transaction t1 = manager.newTransaction();
Map<String, AttributeValue> key1 = newKey(INTEG_HASH_TABLE_NAME);
Map<String, AttributeValue> item1 = new HashMap<String, AttributeValue>(key1);
item1.put("asdf", new AttributeValue("didn't exist"));
Map<String, AttributeValueUpdate> updates1 = new HashMap<String, AttributeValueUpdate>();
updates1.put("asdf", new AttributeValueUpdate(new AttributeValue("didn't exist"), AttributeAction.PUT));
Map<String, AttributeValue> getResult = t1.getItem(new GetItemRequest().withTableName(INTEG_HASH_TABLE_NAME).withKey(key1)).getItem();
assertItemLocked(INTEG_HASH_TABLE_NAME, key1, t1.getId(), true, false);
assertNull(getResult);
Map<String, AttributeValue> updateResult = t1.updateItem(new UpdateItemRequest().withTableName(INTEG_HASH_TABLE_NAME).withKey(key1)
.withAttributeUpdates(updates1).withReturnValues(ReturnValue.ALL_NEW)).getAttributes();
assertItemLocked(INTEG_HASH_TABLE_NAME, key1, item1, t1.getId(), true, true);
assertEquals(item1, updateResult);
t1.commit();
assertItemNotLocked(INTEG_HASH_TABLE_NAME, key1, item1, true);
}
@Test
public void getThenUpdateExistingItem() {
Transaction t1 = manager.newTransaction();
Map<String, AttributeValue> item0a = new HashMap<String, AttributeValue>(item0);
item0a.put("wef", new AttributeValue("new attr"));
Map<String, AttributeValueUpdate> updates1 = new HashMap<String, AttributeValueUpdate>();
updates1.put("wef", new AttributeValueUpdate(new AttributeValue("new attr"), AttributeAction.PUT));
Map<String, AttributeValue> getResult = t1.getItem(new GetItemRequest().withTableName(INTEG_HASH_TABLE_NAME).withKey(key0)).getItem();
assertItemLocked(INTEG_HASH_TABLE_NAME, key0, item0, t1.getId(), false, false);
assertEquals(item0, getResult);
Map<String, AttributeValue> updateResult = t1.updateItem(new UpdateItemRequest().withTableName(INTEG_HASH_TABLE_NAME).withKey(key0)
.withAttributeUpdates(updates1).withReturnValues(ReturnValue.ALL_NEW)).getAttributes();
assertItemLocked(INTEG_HASH_TABLE_NAME, key0, item0a, t1.getId(), false, true);
assertEquals(item0a, updateResult);
t1.commit();
assertItemNotLocked(INTEG_HASH_TABLE_NAME, key0, item0a, true);
}
@Test
public void updateItemAllOldInsert() {
Transaction t1 = manager.newTransaction();
Map<String, AttributeValue> key1 = newKey(INTEG_HASH_TABLE_NAME);
Map<String, AttributeValue> item1 = new HashMap<String, AttributeValue>(key1);
item1.put("asdf", new AttributeValue("wef"));
Map<String, AttributeValueUpdate> updates = new HashMap<String, AttributeValueUpdate>();
updates.put("asdf", new AttributeValueUpdate().withAction(AttributeAction.PUT).withValue(new AttributeValue("wef")));
Map<String, AttributeValue> result1 = t1.updateItem(new UpdateItemRequest()
.withTableName(INTEG_HASH_TABLE_NAME)
.withKey(key1)
.withAttributeUpdates(updates)
.withReturnValues(ReturnValue.ALL_OLD)).getAttributes();
assertItemLocked(INTEG_HASH_TABLE_NAME, key1, item1, t1.getId(), true, true);
assertNull(result1);
t1.commit();
assertItemNotLocked(INTEG_HASH_TABLE_NAME, key1, item1, true);
}
@Test
public void updateItemAllOldOverwrite() {
Transaction t1 = manager.newTransaction();
Map<String, AttributeValue> item1 = new HashMap<String, AttributeValue>(item0);
item1.put("asdf", new AttributeValue("wef"));
Map<String, AttributeValueUpdate> updates = new HashMap<String, AttributeValueUpdate>();
updates.put("asdf", new AttributeValueUpdate().withAction(AttributeAction.PUT).withValue(new AttributeValue("wef")));
Map<String, AttributeValue> result1 = t1.updateItem(new UpdateItemRequest()
.withTableName(INTEG_HASH_TABLE_NAME)
.withKey(key0)
.withAttributeUpdates(updates)
.withReturnValues(ReturnValue.ALL_OLD)).getAttributes();
assertItemLocked(INTEG_HASH_TABLE_NAME, key0, item1, t1.getId(), false, true);
assertEquals(result1, item0);
t1.commit();
assertItemNotLocked(INTEG_HASH_TABLE_NAME, key0, item1, true);
}
@Test
public void updateItemAllNewInsert() {
Transaction t1 = manager.newTransaction();
Map<String, AttributeValue> key1 = newKey(INTEG_HASH_TABLE_NAME);
Map<String, AttributeValue> item1 = new HashMap<String, AttributeValue>(key1);
item1.put("asdf", new AttributeValue("wef"));
Map<String, AttributeValueUpdate> updates = new HashMap<String, AttributeValueUpdate>();
updates.put("asdf", new AttributeValueUpdate().withAction(AttributeAction.PUT).withValue(new AttributeValue("wef")));
Map<String, AttributeValue> result1 = t1.updateItem(new UpdateItemRequest()
.withTableName(INTEG_HASH_TABLE_NAME)
.withKey(key1)
.withAttributeUpdates(updates)
.withReturnValues(ReturnValue.ALL_NEW)).getAttributes();
assertItemLocked(INTEG_HASH_TABLE_NAME, key1, item1, t1.getId(), true, true);
assertEquals(result1, item1);
t1.commit();
assertItemNotLocked(INTEG_HASH_TABLE_NAME, key1, item1, true);
}
@Test
public void updateItemAllNewOverwrite() {
Transaction t1 = manager.newTransaction();
Map<String, AttributeValue> item1 = new HashMap<String, AttributeValue>(item0);
item1.put("asdf", new AttributeValue("wef"));
Map<String, AttributeValueUpdate> updates = new HashMap<String, AttributeValueUpdate>();
updates.put("asdf", new AttributeValueUpdate().withAction(AttributeAction.PUT).withValue(new AttributeValue("wef")));
Map<String, AttributeValue> result1 = t1.updateItem(new UpdateItemRequest()
.withTableName(INTEG_HASH_TABLE_NAME)
.withKey(key0)
.withAttributeUpdates(updates)
.withReturnValues(ReturnValue.ALL_NEW)).getAttributes();
assertItemLocked(INTEG_HASH_TABLE_NAME, key0, item1, t1.getId(), false, true);
assertEquals(result1, item1);
t1.commit();
assertItemNotLocked(INTEG_HASH_TABLE_NAME, key0, item1, true);
}
@Test
public void missingTableName() {
Transaction t1 = manager.newTransaction();
Map<String, AttributeValue> key1 = newKey(INTEG_HASH_TABLE_NAME);
try {
t1.updateItem(new UpdateItemRequest()
.withKey(key1));
fail();
} catch (InvalidRequestException e) {
assertTrue(e.getMessage(), e.getMessage().contains("TableName must not be null"));
}
assertItemNotLocked(INTEG_HASH_TABLE_NAME, key1, false);
t1.rollback();
assertItemNotLocked(INTEG_HASH_TABLE_NAME, key1, false);
t1.delete(Long.MAX_VALUE);
}
@Test
public void roundTripUpdateAll() {
UpdateItem r1 = new UpdateItem();
Map<String, AttributeValue> key = new HashMap<String, AttributeValue>();
key.put(HASH_ATTR_NAME, new AttributeValue("a"));
Map<String, AttributeValueUpdate> updates = new HashMap<String, AttributeValueUpdate>();
updates.put("attr_ss", new AttributeValueUpdate().withAction("PUT").withValue(new AttributeValue().withSS("a", "b")));
updates.put("attr_n", new AttributeValueUpdate().withAction("PUT").withValue(new AttributeValue().withN("1")));
updates.put("attr_ns", new AttributeValueUpdate().withAction("PUT").withValue(new AttributeValue().withNS("1", "2")));
updates.put("attr_b", new AttributeValueUpdate().withAction("PUT").withValue(new AttributeValue().withB(ByteBuffer.wrap(new String("asdf").getBytes()))));
updates.put("attr_bs", new AttributeValueUpdate().withAction("PUT").withValue(new AttributeValue().withBS(ByteBuffer.wrap(new String("asdf").getBytes()), ByteBuffer.wrap(new String("asdf").getBytes()))));
r1.setRequest(new UpdateItemRequest()
.withTableName(TABLE_NAME)
.withKey(key)
.withAttributeUpdates(updates));
byte[] r1Bytes = Request.serialize("123", r1).array();
Request r2 = Request.deserialize("123", ByteBuffer.wrap(r1Bytes));
byte[] r2Bytes = Request.serialize("123", r2).array();
assertArrayEquals(r1Bytes, r2Bytes);
}
@Test
public void roundTripUpdateAllJSON() {
UpdateItem r1 = new UpdateItem();
Map<String, AttributeValue> key = new HashMap<String, AttributeValue>();
key.put(HASH_ATTR_NAME, new AttributeValue("a"));
Map<String, AttributeValueUpdate> updates = new HashMap<String, AttributeValueUpdate>();
updates.put("attr_m", new AttributeValueUpdate().withAction("PUT").withValue(new AttributeValue().withM(JSON_M_ATTR_VAL)));
r1.setRequest(new UpdateItemRequest()
.withTableName(TABLE_NAME)
.withKey(key)
.withAttributeUpdates(updates));
byte[] r1Bytes = Request.serialize("123", r1).array();
Request r2 = Request.deserialize("123", ByteBuffer.wrap(r1Bytes));
byte[] r2Bytes = Request.serialize("123", r2).array();
assertArrayEquals(r1Bytes, r2Bytes);
}
private void executeUpdate(Map<String, AttributeValue> keys, Map<String, AttributeValueUpdate> attributes, Map<String, ExpectedAttributeValue> expected) {
UpdateItemRequest updateEntry = new UpdateItemRequest()
.withTableName(tableName)
.withKey(keys)
.withAttributeUpdates(attributes)
.withExpected(expected);
client.updateItem(updateEntry);
}
@Test
public void testCreateEntry() throws Exception {
RawSecretEntry rawSecretEntry = constructRawEntry(SECRET_NAME);
UpdateItemRequest expectedUpdateRequest = constructUpdateItemRequest(rawSecretEntry, false, Optional.empty());
dynamoDB.create(rawSecretEntry);
verify(mockDynamoDBClient, times(1)).updateItem(expectedUpdateRequest);
}
@Test
public void testUpdateEntry() throws Exception {
RawSecretEntry rawSecretEntry = constructRawEntry(SECRET_NAME);
RawSecretEntry alternativeRawSecretEntry = constructAlternativeRawSecretEntry(SECRET_NAME);
UpdateItemRequest expectedUpdateRequest = constructUpdateItemRequest(rawSecretEntry, true, Optional.of(alternativeRawSecretEntry));
dynamoDB.update(rawSecretEntry, alternativeRawSecretEntry);
verify(mockDynamoDBClient, times(1)).updateItem(expectedUpdateRequest);
}
/**
* Update item into FragmentCheckpoint table for the given input parameters
*
* @param streamName KVS Stream name
* @param fragmentNumber Last processed fragment's fragment number
* @param producerTime Last processed fragment's producer time
* @param serverTime Last processed fragment's server time
* @param updatedTime Time when the entry is going to be updated.
*/
public void updateItem(final String streamName, final String fragmentNumber,
final Long producerTime, final Long serverTime, final Long updatedTime) {
try {
final Map<String,AttributeValue> key = new HashMap<>();
key.put(KVS_STREAM_NAME, new AttributeValue().withS(streamName));
final Map<String,AttributeValueUpdate> updates = new HashMap<>();
updates.put(FRAGMENT_NUMBER, new AttributeValueUpdate().withValue(
new AttributeValue().withS(fragmentNumber)));
updates.put(UPDATED_TIME, new AttributeValueUpdate().withValue(
new AttributeValue().withN(updatedTime.toString())));
updates.put(PRODUCER_TIME, new AttributeValueUpdate().withValue(
new AttributeValue().withN(producerTime.toString())));
updates.put(SERVER_TIME, new AttributeValueUpdate().withValue(
new AttributeValue().withN(serverTime.toString())));
final UpdateItemRequest updateItemRequest = new UpdateItemRequest()
{{
setTableName(TABLE_NAME);
setKey(key);
setAttributeUpdates(updates);
}};
final UpdateItemResult result = ddbClient.updateItem(updateItemRequest);
log.info("Item updated : {}", result.getAttributes());
} catch (final Exception e) {
log.warn("Error while updating item in the table!", e);
}
}
private static void updateMultipleAttributes() {
try {
HashMap<String, AttributeValue> key = new HashMap<String, AttributeValue>();
key.put("Id", new AttributeValue().withN("120"));
Map<String, AttributeValue> expressionAttributeValues = new HashMap<String, AttributeValue>();
expressionAttributeValues.put(":val1", new AttributeValue().withSS("Author YY", "Author ZZ"));
expressionAttributeValues.put(":val2", new AttributeValue().withS("someValue"));
ReturnValue returnValues = ReturnValue.ALL_NEW;
UpdateItemRequest updateItemRequest = new UpdateItemRequest().withTableName(tableName).withKey(key)
.withUpdateExpression("add Authors :val1 set NewAttribute=:val2")
.withExpressionAttributeValues(expressionAttributeValues).withReturnValues(returnValues);
UpdateItemResult result = client.updateItem(updateItemRequest);
// Check the response.
System.out.println("Printing item after multiple attribute update...");
printItem(result.getAttributes());
}
catch (AmazonServiceException ase) {
System.err.println("Failed to update multiple attributes in " + tableName);
System.out.println(ase.getMessage()); // DELETEME
System.err.println("Failed to update multiple attributes in " + tableName); // DELETEME
}
}
private static void updateExistingAttributeConditionally() {
try {
HashMap<String, AttributeValue> key = new HashMap<String, AttributeValue>();
key.put("Id", new AttributeValue().withN("120"));
// Specify the desired price (25.00) and also the condition (price =
// 20.00)
Map<String, AttributeValue> expressionAttributeValues = new HashMap<String, AttributeValue>();
expressionAttributeValues.put(":val1", new AttributeValue().withN("25.00"));
expressionAttributeValues.put(":val2", new AttributeValue().withN("20.00"));
ReturnValue returnValues = ReturnValue.ALL_NEW;
UpdateItemRequest updateItemRequest = new UpdateItemRequest().withTableName(tableName).withKey(key)
.withUpdateExpression("set Price = :val1").withConditionExpression("Price = :val2")
.withExpressionAttributeValues(expressionAttributeValues).withReturnValues(returnValues);
UpdateItemResult result = client.updateItem(updateItemRequest);
// Check the response.
System.out.println("Printing item after conditional update to new attribute...");
printItem(result.getAttributes());
}
catch (ConditionalCheckFailedException cse) {
// Reload object and retry code.
System.err.println("Conditional check failed in " + tableName);
}
catch (AmazonServiceException ase) {
System.err.println("Error updating item in " + tableName);
}
}
public static void updateItem(AmazonDynamoDB dynamoDBClient, String tableName, String id, String val) {
java.util.Map<String, AttributeValue> key = new HashMap<String, AttributeValue>();
key.put("Id", new AttributeValue().withN(id));
Map<String, AttributeValueUpdate> attributeUpdates = new HashMap<String, AttributeValueUpdate>();
AttributeValueUpdate update = new AttributeValueUpdate().withAction(AttributeAction.PUT)
.withValue(new AttributeValue().withS(val));
attributeUpdates.put("attribute-2", update);
UpdateItemRequest updateItemRequest = new UpdateItemRequest().withTableName(tableName).withKey(key)
.withAttributeUpdates(attributeUpdates);
dynamoDBClient.updateItem(updateItemRequest);
}
/**
* This method calculates a lower bound of the size of a new item created with UpdateItem UpdateExpression. It does not
* account for the size of the attribute names of the document paths in the attribute names map and it assumes that the
* UpdateExpression only uses the SET action to assign to top-level attributes.
* @param request UpdateItem request that uses update expressions
* @return the size of the post-update image of the item
*/
private int calculateExpressionBasedUpdateSize(final UpdateItemRequest request) {
if (request == null || request.getUpdateExpression() == null) {
throw new IllegalArgumentException("request did not use update expression");
}
int size = calculateItemSizeInBytes(request.getKey());
for (AttributeValue value : request.getExpressionAttributeValues().values()) {
size += calculateAttributeSizeInBytes(value);
}
return size;
}
@Override
public Collection<MutateWorker> createMutationWorkers(final Map<StaticBuffer, KCVMutation> mutationMap, final DynamoDbStoreTransaction txh) {
final List<MutateWorker> workers = Lists.newLinkedList();
for (Map.Entry<StaticBuffer, KCVMutation> entry : mutationMap.entrySet()) {
final StaticBuffer hashKey = entry.getKey();
final KCVMutation mutation = entry.getValue();
final Map<String, AttributeValue> key = new ItemBuilder().hashKey(hashKey)
.build();
// Using ExpectedAttributeValue map to handle large mutations in a single request
// Large mutations would require multiple requests using expressions
final Map<String, ExpectedAttributeValue> expected =
new SingleExpectedAttributeValueBuilder(this, txh, hashKey).build(mutation);
final Map<String, AttributeValueUpdate> attributeValueUpdates =
new SingleUpdateBuilder().deletions(mutation.getDeletions())
.additions(mutation.getAdditions())
.build();
final UpdateItemRequest request = super.createUpdateItemRequest()
.withKey(key)
.withReturnValues(ReturnValue.ALL_NEW)
.withAttributeUpdates(attributeValueUpdates)
.withExpected(expected);
final MutateWorker worker;
if (mutation.hasDeletions() && !mutation.hasAdditions()) {
worker = new SingleUpdateWithCleanupWorker(request, client.getDelegate());
} else {
worker = new UpdateItemWorker(request, client.getDelegate());
}
workers.add(worker);
}
return workers;
}
@Override
public Object handleRequest(Object input, Context context) {
context.getLogger().log("input: " + input);
if (input.toString().equals("{}") || input.toString().equals("")) {
context.getLogger().log("input is empty: abort");
return "{\"status\":\"error\",\"message\":\"input at lambda function is empty\"}";
}
dynamoDB = new AmazonDynamoDBClient().withRegion(Region
.getRegion(Regions.EU_WEST_1));
HashMap<String, String> mapInput = (HashMap<String, String>) input;
Map<String, AttributeValue> employeeKey = new HashMap<String, AttributeValue>();
String employeeId = mapInput.get("employee_id");
context.getLogger().log("employee_id: " + employeeId);
employeeKey.put("employee_id", new AttributeValue().withS(employeeId));
Map<String, AttributeValueUpdate> attributeUpdates = new HashMap<String, AttributeValueUpdate>();
attributeUpdates.put("approval", new AttributeValueUpdate()
.withValue(new AttributeValue().withS("approved")));
UpdateItemRequest updateItemRequest = new UpdateItemRequest()
.withKey(employeeKey).withAttributeUpdates(attributeUpdates)
.withTableName("lambda-reimbursment");
UpdateItemResult updateItemResult = dynamoDB
.updateItem(updateItemRequest);
context.getLogger().log("Result: " + updateItemResult);
return "{'status':'done'}";
}
private static void updateAddNewAttribute() {
try {
HashMap<String, AttributeValue> key = new HashMap<String, AttributeValue>();
key.put("Id", new AttributeValue().withN("121"));
Map<String, AttributeValue> expressionAttributeValues = new HashMap<String, AttributeValue>();
expressionAttributeValues.put(":val1", new AttributeValue().withS("Some value"));
ReturnValue returnValues = ReturnValue.ALL_NEW;
UpdateItemRequest updateItemRequest = new UpdateItemRequest()
.withTableName(tableName)
.withKey(key)
.withUpdateExpression("set NewAttribute = :val1")
.withExpressionAttributeValues(expressionAttributeValues)
.withReturnValues(returnValues);
UpdateItemResult result = client.updateItem(updateItemRequest);
// Check the response.
System.out.println("Printing item after adding new attribute...");
printItem(result.getAttributes());
} catch (AmazonServiceException ase) {
System.err.println("Failed to add new attribute in " + tableName);
System.err.println(ase.getMessage());
}
}
private static void updateMultipleAttributes() {
try {
HashMap<String, AttributeValue> key = new HashMap<String, AttributeValue>();
key.put("Id", new AttributeValue().withN("120"));
Map<String, AttributeValue> expressionAttributeValues = new HashMap<String, AttributeValue>();
expressionAttributeValues.put(":val1", new AttributeValue().withSS("Author YY", "Author ZZ"));
expressionAttributeValues.put(":val2", new AttributeValue().withS("someValue"));
ReturnValue returnValues = ReturnValue.ALL_NEW;
UpdateItemRequest updateItemRequest = new UpdateItemRequest()
.withTableName(tableName)
.withKey(key)
.withUpdateExpression("add Authors :val1 set NewAttribute=:val2")
.withExpressionAttributeValues(expressionAttributeValues)
.withReturnValues(returnValues);
UpdateItemResult result = client.updateItem(updateItemRequest);
// Check the response.
System.out.println("Printing item after multiple attribute update...");
printItem(result.getAttributes());
} catch (AmazonServiceException ase) {
System.err.println("Failed to update multiple attributes in " + tableName);
System.out.println(ase.getMessage()); //DELETEME
System.err.println("Failed to update multiple attributes in " + tableName); //DELETEME
}
}
private static void updateExistingAttributeConditionally() {
try {
HashMap<String, AttributeValue> key = new HashMap<String, AttributeValue>();
key.put("Id", new AttributeValue().withN("120"));
// Specify the desired price (25.00) and also the condition (price = 20.00)
Map<String, AttributeValue> expressionAttributeValues = new HashMap<String, AttributeValue>();
expressionAttributeValues.put(":val1", new AttributeValue().withN("25.00"));
expressionAttributeValues.put(":val2", new AttributeValue().withN("20.00"));
ReturnValue returnValues = ReturnValue.ALL_NEW;
UpdateItemRequest updateItemRequest = new UpdateItemRequest()
.withTableName(tableName)
.withKey(key)
.withUpdateExpression("set Price = :val1")
.withConditionExpression("Price = :val2")
.withExpressionAttributeValues(expressionAttributeValues)
.withReturnValues(returnValues);
UpdateItemResult result = client.updateItem(updateItemRequest);
// Check the response.
System.out.println("Printing item after conditional update to new attribute...");
printItem(result.getAttributes());
} catch (ConditionalCheckFailedException cse) {
// Reload object and retry code.
System.err.println("Conditional check failed in " + tableName);
} catch (AmazonServiceException ase) {
System.err.println("Error updating item in " + tableName);
}
}
public UpdatePointRequest(GeoPoint geoPoint, AttributeValue rangeKeyValue) {
updateItemRequest = new UpdateItemRequest();
updateItemRequest.setKey(new HashMap<String, AttributeValue>());
updateItemRequest.setAttributeUpdates(new HashMap<String, AttributeValueUpdate>());
this.geoPoint = geoPoint;
this.rangeKeyValue = rangeKeyValue;
}
@Override
public UpdateItemResult updateItem(UpdateItemRequest updateItemRequest) throws AmazonServiceException,
AmazonClientException {
if(requestsToFail.contains(updateItemRequest)) {
throw new FailedYourRequestException();
}
return super.updateItem(updateItemRequest);
}