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; }
/** * Sends an update request to the service and returns true if the request is successful. */ public boolean sendUpdateRequest(Map<String, AttributeValue> primaryKey, Map<String, AttributeValueUpdate> updateItems, Map<String, ExpectedAttributeValue> expectedItems) throws Exception { if (updateItems.isEmpty()) { return false; // No update, return false } UpdateItemRequest updateItemRequest = new UpdateItemRequest().withTableName(tableName).withKey(primaryKey).withReturnValues(ReturnValue.UPDATED_NEW) .withReturnConsumedCapacity(ReturnConsumedCapacity.TOTAL).withAttributeUpdates(updateItems); if (expectedItems != null) { updateItemRequest.withExpected(expectedItems); } UpdateItemResult result = dynamoDBClient.updateItem(updateItemRequest); if(!isRunningOnDDBLocal) { // DDB Local does not support rate limiting tableWriteRateLimiter.adjustRateWithConsumedCapacity(result.getConsumedCapacity()); } return true; }
@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)); }
/** * Move or rename entity to other folder * * @param entity * - current entity want to move or rename * @param newParent * - parent of entity * @param newEntityName * - new name of entity * @param isRenamingAction * - TRUE is renaming file, otherwise FALSE * @return TRUE/FALSE */ @Override public boolean updateEntityByUniqueId(String tableName, Entity entity, Folder newParent, String newEntityName, boolean isRenamingAction) { HashMap<String, AttributeValue> primaryKey = new HashMap<String, AttributeValue>(); primaryKey.put(AttributeKey.UUID, new AttributeValue().withS(entity.getId().toString())); Map<String, AttributeValueUpdate> updateItems = new HashMap<String, AttributeValueUpdate>(); updateItems.put(AttributeKey.ENTITY_NAME, new AttributeValueUpdate() .withAction(AttributeAction.PUT).withValue(new AttributeValue().withS(newEntityName))); updateItems.put(AttributeKey.MODIFIED_DATE, new AttributeValueUpdate() .withAction(AttributeAction.PUT).withValue(new AttributeValue().withS(DateUtils.dateToString(new Date())))); if (!isRenamingAction) { updateItems.put(AttributeKey.PARENT_UUID, new AttributeValueUpdate() .withAction(AttributeAction.PUT).withValue(new AttributeValue() .withS(newParent.getId().toString()))); } UpdateItemResult updateStatus = dynamoDBService.updateItem(tableName, primaryKey, updateItems); if (updateStatus != null) { return true; } return false; }
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; }
public CompletableFuture<UpdateItemResult> updateItem(final String tableName, final Map<String, AttributeValue> key, final Map<String, AttributeValueUpdate> attributeUpdates) { return asyncExecutor.execute(new Callable<UpdateItemResult>() { @Override public UpdateItemResult call() throws Exception { return dbExecutor.updateItem(tableName, key, attributeUpdates); } }); }
public CompletableFuture<UpdateItemResult> updateItem(final String tableName, final Map<String, AttributeValue> key, final Map<String, AttributeValueUpdate> attributeUpdates, final String returnValues) { return asyncExecutor.execute(new Callable<UpdateItemResult>() { @Override public UpdateItemResult call() throws Exception { return dbExecutor.updateItem(tableName, key, attributeUpdates, returnValues); } }); }
public CompletableFuture<UpdateItemResult> updateItem(final UpdateItemRequest updateItemRequest) { return asyncExecutor.execute(new Callable<UpdateItemResult>() { @Override public UpdateItemResult call() throws Exception { return dbExecutor.updateItem(updateItemRequest); } }); }
@Override public void execute() { UpdateItemResult result = ddbClient.updateItem(new UpdateItemRequest() .withTableName(determineTableName()) .withKey(determineKey()) .withAttributeUpdates(determineUpdateValues()) .withExpected(determineUpdateCondition()) .withReturnValues(determineReturnValues())); addAttributesToResult(result.getAttributes()); }
@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'}"; }
@Override public UpdateItemResult updateItem(String tableName, HashMap<String, AttributeValue> primaryKey, Map<String, AttributeValueUpdate> updateItems) { Map<String, AttributeValueUpdate> attributeValueUpdates = new HashMap<String, AttributeValueUpdate>(); attributeValueUpdates.putAll(updateItems); UpdateItemRequest updateItemRequest = new UpdateItemRequest() .withTableName(tableName) .withKey(primaryKey).withReturnValues(ReturnValue.UPDATED_NEW) .withAttributeUpdates(updateItems); UpdateItemResult updateItemResult = dynamoDBClient.updateItem(updateItemRequest); LOG.info("Successful by updating item from " + tableName + ": " + updateItemResult); return updateItemResult; }
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 Map<String, AttributeValue> put( final Map<String, AttributeValueUpdate> attrs) throws IOException { final AmazonDynamoDB aws = this.credentials.aws(); final Attributes expected = this.attributes.only(this.keys); try { final UpdateItemRequest request = new UpdateItemRequest() .withTableName(this.name) .withExpected(expected.asKeys()) .withKey(expected) .withAttributeUpdates(attrs) .withReturnConsumedCapacity(ReturnConsumedCapacity.TOTAL) .withReturnValues(ReturnValue.UPDATED_NEW); final long start = System.currentTimeMillis(); final UpdateItemResult result = aws.updateItem(request); Logger.info( this, "#put('%s'): updated item to DynamoDB, %s, in %[ms]s", attrs, new PrintableConsumedCapacity( result.getConsumedCapacity() ).print(), System.currentTimeMillis() - start ); return result.getAttributes(); } catch (final AmazonClientException ex) { throw new IOException( String.format( "failed to put %s into \"%s\" with %s", attrs, this.name, this.keys ), ex ); } finally { aws.shutdown(); } }
public UpdateItemResult updateItem(final String tableName, final Map<String, AttributeValue> key, final Map<String, AttributeValueUpdate> attributeUpdates) { return dynamoDB.updateItem(tableName, key, attributeUpdates); }
public UpdateItemResult updateItem(final String tableName, final Map<String, AttributeValue> key, final Map<String, AttributeValueUpdate> attributeUpdates, final String returnValues) { return dynamoDB.updateItem(tableName, key, attributeUpdates, returnValues); }
public UpdateItemResult updateItem(final UpdateItemRequest updateItemRequest) { return dynamoDB.updateItem(updateItemRequest); }
@Override public UpdateItemResult updateItem(UpdateItemRequest updateItemRequest) { this.updateItemRequest = updateItemRequest; return new UpdateItemResult().withAttributes(getAttributes()); }
@Override protected UpdateItemResult call() throws BackendException { return delegate.updateItem(request); }
public UpdateItemResult updateConditionalValue(final AmazonDynamoDB dynamoClient, final String tableName, final UpdateKey key, final String attribute, final AggregateAttributeModification update) throws Exception { Map<String, AttributeValue> updateKey = StreamAggregatorUtils.getTableKey(key); UpdateItemResult result; final ReturnValue returnValue = ReturnValue.UPDATED_NEW; final String setAttribute = StreamAggregatorUtils.methodToColumn(attribute); // create the update that we want to write final Map<String, AttributeValueUpdate> thisCalcUpdate = new HashMap<String, AttributeValueUpdate>() { { put(setAttribute, new AttributeValueUpdate().withAction(AttributeAction.PUT).withValue( new AttributeValue().withN("" + update.getFinalValue()))); } }; // create the request UpdateItemRequest req = new UpdateItemRequest().withTableName(tableName).withKey(updateKey).withReturnValues( returnValue).withAttributeUpdates(thisCalcUpdate); Map<String, ExpectedAttributeValue> expected = new HashMap<>(); final SummaryCalculation calc = update.getCalculationApplied(); // try an update to PUT the value if NOT EXISTS, to establish if we // are the first writer for this key expected = new HashMap<String, ExpectedAttributeValue>() { { put(setAttribute, new ExpectedAttributeValue().withExists(false)); } }; req.setExpected(expected); try { result = DynamoUtils.updateWithRetries(dynamoClient, req); // yay - we were the first writer, so our value was written return result; } catch (ConditionalCheckFailedException e1) { // set the expected to the comparison contained in the update // calculation expected.clear(); expected.put( setAttribute, new ExpectedAttributeValue().withComparisonOperator( calc.getDynamoComparisonOperator()).withValue( new AttributeValue().withN("" + update.getFinalValue()))); req.setExpected(expected); // do the conditional update on the summary // calculation. this may result in no update being // applied because the new value is greater than the // current minimum for MIN, or less than the current // maximum for MAX. try { result = DynamoUtils.updateWithRetries(dynamoClient, req); return result; } catch (ConditionalCheckFailedException e2) { // no worries - we just weren't the min or max! return null; } } }
@Override public <T extends Message> boolean update(T item, Modifier... modifiers) throws DataStoreException { DynamoClassMapping<T> tableInfo = getClassMapping(item); log.debug("Update {} {} [{}]", item.getClass().getSimpleName(), item, modifiers); UpdateItemRequest request = new UpdateItemRequest(); request.setTableName(tableInfo.getDynamoTableName()); request.setKey(tableInfo.buildCompleteKey(item)); Map<String, ExpectedAttributeValue> expected = Maps.newHashMap(); expected.put(FIELD_HASH_KEY, new ExpectedAttributeValue().withComparisonOperator(ComparisonOperator.NOT_NULL)); for (Modifier modifier : modifiers) { if (modifier instanceof WhereModifier) { WhereModifier where = (WhereModifier) modifier; Map<FieldDescriptor, Object> matcherFields = where.getMatcher().getAllFields(); for (Map.Entry<FieldDescriptor, Object> matcherField : matcherFields.entrySet()) { FieldDescriptor fieldDescriptor = matcherField.getKey(); Object fieldValue = matcherField.getValue(); tableInfo.addFilter(expected, fieldDescriptor, fieldValue); } } else { throw new UnsupportedOperationException(); } } Map<String, AttributeValueUpdate> attributeUpdates = tableInfo.mapToUpdate(item); request.setAttributeUpdates(attributeUpdates); request.setExpected(expected); if (expected.size() > 1) { request.setConditionalOperator(ConditionalOperator.AND); } try { UpdateItemResult response = dynamoDB.updateItem(request); return true; } catch (ConditionalCheckFailedException e) { log.debug("Update failed (conditional check failed)"); return false; } }
public UpdatePointResult(UpdateItemResult updateItemResult) { this.updateItemResult = updateItemResult; }
public UpdateItemResult getUpdateItemResult() { return updateItemResult; }
/** * Edits an existing item's attributes. You can perform a conditional update * (insert a new attribute name-value pair if it doesn't exist, or replace * an existing name-value pair if it has certain expected attribute values). * * @param tableName * - The name of the table * @param primaryKey * - The primary key of the item * @param updateItems * - The new expected attribute values * @return */ UpdateItemResult updateItem(String tableName, HashMap<String, AttributeValue> primaryKey, Map<String, AttributeValueUpdate> updateItems);