【问题标题】:DynamoDB mapper conditional save failing for new row updatesDynamoDB 映射器有条件保存新行更新失败
【发布时间】:2019-06-06 00:42:31
【问题描述】:

假设我在 DDB 中有下表。一个哈希键(我们称之为“名称”)、一个范围键(我们称之为“活动”)和一个属性(我们称之为“日期”)

|---------------------|------------------|------------------|
|       HashKey(S)    |     RangeKey(S)  |      Date(S)     |
|---------------------|------------------|------------------|  
|          Sam        |     Fishing      |      2019        |  
|---------------------|------------------|------------------|
|          Sam        |     Kayaking     |      2019        |  
|---------------------|------------------|------------------|
|          Peter      |     Kayaking     |      2019        | 
|---------------------|------------------|------------------|

我想对此进行有条件的保存,以便我想添加一个新的“名称+活动”并在数据库中保持最新的日期。所以这两种可能性的细分是

1) 如果已经存在基于我传递到保存中的哈希+范围键,我想检查我的条件表达式,如果失败则不更新。
2)如果是新的hash+rangekey,我想创建一个新行,而不是检查我的条件表达式(因为表中没有值要检查)

我尝试过的一个例子

public void methodToDoSave() {
  final Map<String, ExpectedAttributeValue> expectedAttributes = 
      getExpectedAttributes(date);
  final DynamoDBSaveExpression saveExpression = new DynamoDBSaveExpression()
      .withExpected(expectedAttributes);
  mapper.save(dbItem, saveExpression);
}

private Map<String, ExpectedAttributeValue> getExpectedAttributes(
        final Date date){

    final Map expectedAttributeSetupForConditionalUpdate = new HashMap();
    expectedAttributeSetupForConditionalUpdate
            .put("Date",new ExpectedAttributeValue(new AttributeValue().withS(date))
                            .withComparisonOperator(ComparisonOperator.LE));
    return expectedAttributeSetupForConditionalUpdate;
}

当哈希+范围键已经在表中时,这适用于进行条件检查和成功/通过,但是如果我提供新的范围键,条件检查似乎总是失败。

条件检查的堆栈跟踪对于向我解释问题没有多大用处,但我的假设是条件检查甚至适用于全新的行创建,因此它失败了。

有没有办法让这个在一个保存操作中工作,或者我需要先阅读,检查是否存在,如果是,则不进行条件检查保存,如果没有条件检查保存?

【问题讨论】:

标签: amazon-dynamodb dynamodb-queries


【解决方案1】:

我能够利用上面 Tawan 的提示并做这样的事情。

final Map expectedAttributeSetupForConditionalUpdate = new HashMap();

expectedAttributeSetupForConditionalUpdate
  .put("name", new ExpectedAttributeValue().withExists(false));
expectedAttributeSetupForConditionalUpdate
  .put("activity", new ExpectedAttributeValue().withExists(false));
expectedAttributeSetupForConditionalUpdate
  .put("Date", new ExpectedAttributeValue(new AttributeValue().withS(date))
  .withComparisonOperator(ComparisonOperator.LE));

final DynamoDBSaveExpression saveExpression = new DynamoDBSaveExpression() .withExpected(expectedAttributeSetupForConditionalUpdate)
.withConditionalOperator(ConditionalOperator.OR);

我无法使用较新的 Condition 表达式,因为 DynamoDB 映射器在我使用的版本中还不支持它们。本质上,当该行不存在时,这“通过”条件检查,但在它存在时使用日期。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-29
    • 2010-11-06
    • 2019-05-03
    • 1970-01-01
    相关资源
    最近更新 更多