【发布时间】: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;
}
当哈希+范围键已经在表中时,这适用于进行条件检查和成功/通过,但是如果我提供新的范围键,条件检查似乎总是失败。
条件检查的堆栈跟踪对于向我解释问题没有多大用处,但我的假设是条件检查甚至适用于全新的行创建,因此它失败了。
有没有办法让这个在一个保存操作中工作,或者我需要先阅读,检查是否存在,如果是,则不进行条件检查保存,如果没有条件检查保存?
【问题讨论】:
-
我不知道这是否能解决问题,但我会尝试使用函数 attribute_exists [1] 使用 OR 子句扩展条件,以便当日期属性不存在时条件通过存在 [1] docs.aws.amazon.com/amazondynamodb/latest/developerguide/…
标签: amazon-dynamodb dynamodb-queries