下面列出了怎么用com.amazonaws.services.dynamodbv2.model.UpdateItemResult的API类实例代码及写法,或者点击链接到github查看源代码。
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;
}
@Override
public Void call() throws BackendException {
final UpdateItem updateBackoff = new UpdateItem(updateItemRequest, dynamoDbDelegate);
final UpdateItemResult result = updateBackoff.runWithBackoff();
final Map<String, AttributeValue> item = result.getAttributes();
if (item == null) {
// bail
return null;
}
// If the record has no Titan columns left after deletions occur, then just delete the record
if (item.containsKey(Constants.JANUSGRAPH_HASH_KEY) && item.size() == ATTRIBUTES_IN_EMPTY_SINGLE_ITEM) {
final DeleteItem deleteBackoff = new DeleteItem(new DeleteItemRequest().withTableName(updateItemRequest.getTableName())
.withKey(updateItemRequest.getKey()), dynamoDbDelegate);
deleteBackoff.runWithBackoff();
}
// void
return null;
}
@Test
public void test_updateItem_WithAllParameters() throws Exception {
createTable();
putItem(TEST_ATTRIBUTE, TEST_ATTRIBUTE_VALUE);
String UPDATE_ATTRIBUTE_VALUE = "UpdateAttributeValue1";
Map<String, AttributeValue> key = new HashMap<String, AttributeValue>();
key.put(TEST_ATTRIBUTE, new AttributeValue()
.withS(TEST_ATTRIBUTE_VALUE));
Map<String, AttributeValueUpdate> attributeUpdates = new HashMap<String, AttributeValueUpdate>();
attributeUpdates.put(TEST_ATTRIBUTE, new AttributeValueUpdate()
.withAction(AttributeAction.PUT)
.withValue(new AttributeValue()
.withS(UPDATE_ATTRIBUTE_VALUE)));
String returnValues = "";
UpdateItemResult result = dynamoDb.updateItem(TEST_TABLE_NAME, key, attributeUpdates, returnValues);
Double units = result.getConsumedCapacity().getCapacityUnits();
GetItemResult getItemResult = getItem(TEST_ATTRIBUTE, UPDATE_ATTRIBUTE_VALUE);
String updatedValue = getItemResult.getItem().get(TEST_ATTRIBUTE).getS();
assertThat(units.doubleValue(), equalTo(1.0));
assertThat(updatedValue, equalTo(UPDATE_ATTRIBUTE_VALUE));
}
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;
}
@Override
public UpdateItemResult updateItem(
String tableName,
Map<String, AttributeValue> key,
Map<String, AttributeValueUpdate> attributeUpdates) {
throw new UnsupportedOperationException();
}
TestItem(TableSchema<?> schema,
Object v2Bean,
UpdateItemResponse v2UpdateItemResponse,
Object v1Bean,
UpdateItemResult v1UpdateItemResult) {
this.schema = schema;
this.v2Bean = v2Bean;
this.v2UpdateItemResponse = v2UpdateItemResponse;
this.v1Bean = v1Bean;
this.v1UpdateItemResult = v1UpdateItemResult;
}
/**
* 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);
}
}
@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);
}
}
@Override
public UpdateItemResult updateItem(UpdateItemRequest updateItemRequest) throws AmazonServiceException,
AmazonClientException {
if(requestsToFail.contains(updateItemRequest)) {
throw new FailedYourRequestException();
}
return super.updateItem(updateItemRequest);
}
/**
* Adds an UpdateItem request to the transaction
*
* @param request
* @throws DuplicateRequestException if the item in the request is already involved in this transaction
* @throws ItemNotLockedException when another transaction is confirmed to have the lock on the item in the request
* @throws TransactionCompletedException when the transaction has already completed
* @throws TransactionNotFoundException if the transaction does not exist
* @throws TransactionException on unexpected errors or unresolvable OCC contention
*/
public UpdateItemResult updateItem(UpdateItemRequest request)
throws DuplicateRequestException, ItemNotLockedException,
TransactionCompletedException, TransactionNotFoundException, TransactionException {
UpdateItem wrappedRequest = new UpdateItem();
wrappedRequest.setRequest(request);
Map<String, AttributeValue> item = driveRequest(wrappedRequest);
stripSpecialAttributes(item);
return new UpdateItemResult().withAttributes(item);
}
@Override
public UpdateItemResult updateItem(String tableName,
Map<String, AttributeValue> key,
Map<String, AttributeValueUpdate> attributeUpdates)
throws AmazonServiceException, AmazonClientException {
throw new UnsupportedOperationException("Use the underlying client instance instead");
}
@Override
public UpdateItemResult updateItem(String tableName,
Map<String, AttributeValue> key,
Map<String, AttributeValueUpdate> attributeUpdates,
String returnValues) throws AmazonServiceException,
AmazonClientException {
throw new UnsupportedOperationException("Use the underlying client instance instead");
}
/**
* Marks the transaction item as either COMMITTED or ROLLED_BACK, but only if it was in the PENDING state.
* It will also condition on the expected version.
*
* @param targetState
* @param expectedVersion
* @throws ConditionalCheckFailedException if the transaction doesn't exist, isn't PENDING, is finalized,
* or the expected version doesn't match (if specified)
*/
public void finish(final State targetState, final int expectedVersion) throws ConditionalCheckFailedException {
txAssert(State.COMMITTED.equals(targetState) || State.ROLLED_BACK.equals(targetState),"Illegal state in finish(): " + targetState, "txItem", txItem);
Map<String, ExpectedAttributeValue> expected = new HashMap<String, ExpectedAttributeValue>(2);
expected.put(AttributeName.STATE.toString(), new ExpectedAttributeValue().withValue(new AttributeValue().withS(STATE_PENDING)));
expected.put(AttributeName.FINALIZED.toString(), new ExpectedAttributeValue().withExists(false));
expected.put(AttributeName.VERSION.toString(), new ExpectedAttributeValue().withValue(new AttributeValue().withN(Integer.toString(expectedVersion))));
Map<String, AttributeValueUpdate> updates = new HashMap<String, AttributeValueUpdate>();
updates.put(AttributeName.STATE.toString(), new AttributeValueUpdate()
.withAction(AttributeAction.PUT)
.withValue(new AttributeValue(stateToString(targetState))));
updates.put(AttributeName.DATE.toString(), new AttributeValueUpdate()
.withAction(AttributeAction.PUT)
.withValue(txManager.getCurrentTimeAttribute()));
UpdateItemRequest finishRequest = new UpdateItemRequest()
.withTableName(txManager.getTransactionTableName())
.withKey(txKey)
.withAttributeUpdates(updates)
.withReturnValues(ReturnValue.ALL_NEW)
.withExpected(expected);
UpdateItemResult finishResult = txManager.getClient().updateItem(finishRequest);
txItem = finishResult.getAttributes();
if(txItem == null) {
throw new TransactionAssertionException(txId, "Unexpected null tx item after committing " + targetState);
}
}
@Override
public UpdateItemResult updateItem(UpdateItemRequest request)
throws AmazonServiceException, AmazonClientException {
Map<String, ExpectedAttributeValue> expectedValues = request.getExpected();
checkExpectedValues(request.getTableName(), request.getKey(), expectedValues);
// conditional checks are handled by the above call
request.setExpected(null);
return txn.updateItem(request);
}
@Override
public UpdateItemResult updateItem(String tableName,
Map<String, AttributeValue> key,
Map<String, AttributeValueUpdate> attributeUpdates)
throws AmazonServiceException, AmazonClientException {
return updateItem(new UpdateItemRequest()
.withTableName(tableName)
.withKey(key)
.withAttributeUpdates(attributeUpdates));
}
@Override
public UpdateItemResult updateItem(String tableName,
Map<String, AttributeValue> key,
Map<String, AttributeValueUpdate> attributeUpdates,
String returnValues) throws AmazonServiceException,
AmazonClientException {
return updateItem(new UpdateItemRequest()
.withTableName(tableName)
.withKey(key)
.withAttributeUpdates(attributeUpdates)
.withReturnValues(returnValues));
}
@Override
public UpdateItemResult updateItem(UpdateItemRequest updateItemRequest) {
throw new UnsupportedOperationException();
}
@Override
public UpdateItemResult updateItem(String tableName, Map<String, AttributeValue> key,
Map<String, AttributeValueUpdate> attributeUpdates, String returnValues) {
throw new UnsupportedOperationException();
}
private static AmazonDynamoDB getV1Client(Blackhole bh, UpdateItemResult updateItemResult) {
return new V1TestDynamoDbUpdateItemClient(bh, updateItemResult);
}
public V1TestDynamoDbUpdateItemClient(Blackhole bh, UpdateItemResult updateItemResult) {
super(bh);
this.updateItemResult = updateItemResult;
}
@Override
public UpdateItemResult updateItem(UpdateItemRequest request) {
bh.consume(request);
return updateItemResult;
}
@Override
protected UpdateItemResult call() throws BackendException {
return delegate.updateItem(request);
}
/**
* {@inheritDoc}
*/
@SuppressWarnings("unchecked")
@Override
public List<Record> emit(final UnmodifiableBuffer<Record> buffer) {
if (isShutdown) {
if (buffer.getRecords().isEmpty()) {
// This is OK, but not expected
log.warn("Record processor called emit after calling shutdown. Continuing becuase buffer is empty.");
return Collections.emptyList();
} else {
throw new IllegalStateException("Cannot emit records after emitter has been shutdown.");
}
}
// Asynchronously process all writes, but block on the results.
List<Record> records = buffer.getRecords();
// Stores records that failed with a non-retryable exception
final List<Record> failedRecords = Collections.synchronizedList(new ArrayList<Record>());
// Queue of records to submit
final BlockingQueue<Record> toSubmit = new LinkedBlockingQueue<Record>(records);
// Used to detect when all requests have either succeeded or resulted in a non-retryable exception
final CountDownLatch doneSignal = new CountDownLatch(records.size());
final AtomicInteger retryCount = new AtomicInteger();
boolean interrupted = false;
try {
while (doneSignal.getCount() > 0) {
Record recordToSubmit = null;
try {
recordToSubmit = toSubmit.poll(WAIT_TIME_MS, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
interrupted = true;
}
final Record record = recordToSubmit;
if (null == record) {
continue; // Check if all records have completed and if not try to poll again
}
// Generate the request based on the record
AmazonWebServiceRequest request = createRequest(record);
if (request == null) { // Should only happen if DynamoDB Streams API updates to support different operations
// than {INSERT, MODIFY, REMOVE}.
continue;
}
// Submit the write request based on its type
if (request instanceof PutItemRequest) { // PUT
getDynamodb().putItemAsync((PutItemRequest) request,
(AsyncHandler<PutItemRequest, PutItemResult>) getHandler(toSubmit, failedRecords, retryCount, doneSignal, record));
} else if (request instanceof DeleteItemRequest) { // DELETE
getDynamodb().deleteItemAsync((DeleteItemRequest) request,
(AsyncHandler<DeleteItemRequest, DeleteItemResult>) getHandler(toSubmit, failedRecords, retryCount, doneSignal, record));
} else if (request instanceof UpdateItemRequest) { // UPDATE
getDynamodb().updateItemAsync((UpdateItemRequest) request,
(AsyncHandler<UpdateItemRequest, UpdateItemResult>) getHandler(toSubmit, failedRecords, retryCount, doneSignal, record));
} else { // Should only happen if DynamoDB allows a new operation other than {PutItem, DeleteItem,
// UpdateItem} for single item writes.
log.warn("Unsupported DynamoDB request: " + request);
}
}
} finally {
if (interrupted) {
Thread.currentThread().interrupt();
}
}
emitCloudWatchMetrics(records, failedRecords, retryCount);
if (!records.isEmpty()) {
log.debug("Successfully emitted " + (records.size() - failedRecords.size()) + " records ending with sequence number "
+ buffer.getLastSequenceNumber());
} else {
log.debug("No records to emit");
}
return failedRecords;
}
public UpdatePointResult(UpdateItemResult updateItemResult) {
this.updateItemResult = updateItemResult;
}