В предыдущем посте мы приступили к вставке элементов в DynamoDB с использованием Java. DynamoDB также поддерживает обновление элементов.
Мы будем использовать таблицу Login для примеров обновления.
При выпуске обновления необходимо указать первичный ключ элемента, который вы хотите обновить.
|
01
02
03
04
05
06
07
08
09
10
11
12
13
14
|
public void updateName(String email,String fullName) { Map<String,AttributeValue> attributeValues = new HashMap<>(); attributeValues.put("email",new AttributeValue().withS(email)); attributeValues.put("fullname",new AttributeValue().withS(fullName)); UpdateItemRequest updateItemRequest = new UpdateItemRequest() .withTableName(TABLE_NAME) .addKeyEntry("email",new AttributeValue().withS(email)) .addAttributeUpdatesEntry("fullname", new AttributeValueUpdate().withValue(new AttributeValue().withS(fullName))); UpdateItemResult updateItemResult = amazonDynamoDB.updateItem(updateItemRequest); } |
Мы можем перейти к более сложным утверждениям, используя условные обновления. Условные обновления могут помочь нам во многих случаях, таких как обработка одновременных обновлений.
Мы можем добиться этого с помощью простых выражений.
|
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
|
public void updateConditionallyWithExpression(String email,String fullName,String prefix) { Map<String, AttributeValue> key = new HashMap<>(); key.put("email", new AttributeValue().withS(email)); Map<String, AttributeValue> attributeValues = new HashMap<>(); attributeValues.put(":prefix", new AttributeValue().withS(prefix)); attributeValues.put(":fullname", new AttributeValue().withS(fullName)); UpdateItemRequest updateItemRequest = new UpdateItemRequest() .withTableName(TABLE_NAME) .withKey(key) .withUpdateExpression("set fullname = :fullname") .withConditionExpression("begins_with(fullname,:prefix)") .withExpressionAttributeValues(attributeValues); UpdateItemResult updateItemResult = amazonDynamoDB.updateItem(updateItemRequest); } |
Или путем указания атрибутов.
|
01
02
03
04
05
06
07
08
09
10
11
12
13
|
public void updateConditionallyWithAttributeEntries(String email, String fullName, String prefix){ Map<String,AttributeValue> key = new HashMap<>(); key.put("email",new AttributeValue().withS(email)); UpdateItemRequest updateItemRequest = new UpdateItemRequest() .withTableName(TABLE_NAME) .withKey(key) .addAttributeUpdatesEntry("fullname",new AttributeValueUpdate().withValue(new AttributeValue().withS(fullName)).withAction(AttributeAction.PUT)) .addExpectedEntry("fullname",new ExpectedAttributeValue().withValue(new AttributeValue().withS(prefix)).withComparisonOperator(ComparisonOperator.BEGINS_WITH)); UpdateItemResult updateItemResult = amazonDynamoDB.updateItem(updateItemRequest); } |
Еще одна особенность — атомные счетчики. Мы можем выпускать обновления для элемента DynamoDB и увеличивать значения атрибутов. Мы добавим дополнительное поле с именем count. Также мы добавим еще одну функцию обновления. После вызова функция обновит указанное поле, но также увеличит атрибут счетчика. Таким образом, атрибут counter будет отображать, сколько раз и обновление было выполнено для определенного элемента.
|
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
public void addUpdateCounter(String email) { Map<String,AttributeValue> key = new HashMap<>(); key.put("email",new AttributeValue().withS(email)); UpdateItemRequest updateItemRequest = new UpdateItemRequest() .withTableName(TABLE_NAME) .withKey(key) .addAttributeUpdatesEntry("counter",new AttributeValueUpdate().withValue(new AttributeValue().withN("0")).withAction(AttributeAction.PUT)); UpdateItemResult updateItemResult = amazonDynamoDB.updateItem(updateItemRequest); } public void updateAndIncreaseCounter(String email,String fullname) { Map<String,AttributeValue> key = new HashMap<>(); key.put("email",new AttributeValue().withS(email)); UpdateItemRequest updateItemRequest = new UpdateItemRequest() .withTableName(TABLE_NAME) .withKey(key) .addAttributeUpdatesEntry("fullname",new AttributeValueUpdate().withValue(new AttributeValue().withS(fullname)).withAction(AttributeAction.PUT)) .addAttributeUpdatesEntry("counter",new AttributeValueUpdate().withValue(new AttributeValue().withN("1")).withAction(AttributeAction.ADD)); UpdateItemResult updateItemResult = amazonDynamoDB.updateItem(updateItemRequest); } |
Вы можете найти исходный код на github .
| Ссылка: | Обновите элементы DynamoDB с помощью Java от нашего партнера по JCG Эммануила Гкатзиураса в блоге gkatzioura |