DynamoDB:ConditionalCheckFailedException

时间:2016-10-06 19:27:02

标签: java amazon-dynamodb amazon-dynamodb-streams

我正在处理ConditionalCheckFailedException并且我不确定哪个条件未通过检查。当我打开调试器并检查异常变量时,我找不到任何有用的信息。

以下是我的Java Dynamo客户端代码。我试图在以下情况下使用DynamoDBSaveExpression对DynamoDB进行条件写入:

表中的客户日期在我尝试写入的当前客户日期之前(存储为EPOCH时间) 表中不存在条目(我检查FEEDBACK_KEY,因为它是我表中的主键) 当我将第一个条目写入表时,它可以正常工作,但是当条目存在时,在更新时,我得到ConditionalCheckFailedException异常。有什么想法吗?

final DynamoDBSaveExpression expression = new DynamoDBSaveExpression();

final Map<String, ExpectedAttributeValue> expectedAttributes =
        ImmutableMap.<String, ExpectedAttributeValue>builder()
            .put(ThemesMessageEligibility.TableKeys.CLIENT_DATE,
                    new ExpectedAttributeValue()
                        .withComparisonOperator(ComparisonOperator.LT)
                        .withValue(new AttributeValue().withN(clientDate)))
            .put(ThemesMessageEligibility.TableKeys.FEEDBACK_KEY,
                    new ExpectedAttributeValue(false))
            .build();

expression.setExpected(expectedAttributes);
expression.setConditionalOperator(ConditionalOperator.OR);

// Conditional write if the clientDate is after the dynamo's client Date
try {
    dynamoMapper.save(themesFeedbackComponentContainer, expression);
} catch (ConditionalCheckFailedException ex) {
   ...
}

1 个答案:

答案 0 :(得分:1)

我会删除第二个条件,或者更改它以使条件存在于现有项目(new ExpectedAttributeValue(true))上。即使现有项目存在,UpdateItem也会覆盖现有项目,因此看起来CLIENT_DATE条件是您唯一需要的条件。

上面写的API调用只会在第一次写入时成功(即,当项目不存在时)。回想起来,如果您只希望对项目的第一次写入成功(如果项目已存在则失败),则不需要CLIENT_DATE条件(因为现有图像中没有要比较的属性)。