2017-04-23 37 views
0

是否可以運行鍼對亞馬遜DynamoDB的請求的updateItem用,如果該項目不存在,將永遠成功的條件存在。例如:如何通過條件檢查,如果項目不與AWS DynamoDB的updateItem要求

long timestampNow = System.currentTimeMillis(); 

UpdateItemSpec updateItemSpec = new UpdateItemSpec() 
     .withPrimaryKey("primary_key", theKey) 
     .withReturnValues(ReturnValue.ALL_NEW) 
     .withAttributeUpdate(
       new AttributeUpdate("my_attr").put(timestampNow+SOME_DURATION)) 
     .withExpected(
       new Expected("my_attr").lt(timestampNow)); 
try { 
    UpdateItemOutcome outcome = AWS.DYNAMO_DOC.getTable("my_table").updateItem(updateItemSpec); 
    return outcome.getUpdateItemResult().getAttributes(); 

} catch (ConditionalCheckFailedException e) { 
    return null; 
} 

當我做了的項目,目前還不存在請求時,它拋出ConditionalCheckFailedException,但我想它通過條件測試,只是繼續創建項目。那可能嗎?

回答

0

該文檔實際上擁有了一切我需要知道:

long timestampNow = System.currentTimeMillis(); 

UpdateItemSpec updateItemSpec = new UpdateItemSpec() 
     .withPrimaryKey("primary_key", theKey) 
     .withReturnValues(ReturnValue.ALL_NEW) 
     .withConditionExpression("attribute_not_exists(my_attr) or my_attr < :now") 
     .withUpdateExpression("SET my_attr = :exp") 
     .withValueMap(new ValueMap() 
       .withLong(":now", timestampNow) 
       .withLong(":exp", timestampNow+LOCK_EXPIRY_DURATION)); 
try { 
    UpdateItemOutcome outcome = AWS.DYNAMO_DOC.getTable("my_table").updateItem(updateItemSpec); 
    return outcome.getUpdateItemResult().getAttributes(); 

} catch (ConditionalCheckFailedException e) { 
    return null; 
}