2017-02-06 16 views
1

java sdkを使用してDynamoDBのDynamoDBSaveExpressionを使用しようとしています。私は次の2つのシナリオをエミュレートしようとしている位置にいるDynamoDBの式 - 複数のExpectedAttributeValuesの比較

1)項目がテーブルに存在する場合は、保存表現の制限DATE1、DATE2、およびDATE3(以下のコードを参照)を強制するには。

2)アイテムがテーブルに存在しない場合は、挿入してください。ここで

は、これまでの私のコードです:

 ExpectedAttributeValue date1 = new ExpectedAttributeValue() 
       .withComparisonOperator(ComparisonOperator.LE) 
       .withValue(new AttributeValue().withN(Long.toString(tr.date1().getTime()))); 

     ExpectedAttributeValue date2 = new ExpectedAttributeValue() 
       .withComparisonOperator(ComparisonOperator.LE) 
       .withValue(new AttributeValue().withN(Long.toString(tr.date2().getTime()))); 

     ExpectedAttributeValue date3 = new ExpectedAttributeValue() 
       .withComparisonOperator(ComparisonOperator.LE) 
       .withValue(new AttributeValue().withN(Long.toString(tr.date3().getTime()))); 



     DynamoDBSaveExpression saveExpression = new DynamoDBSaveExpression(); 
     Map<String, ExpectedAttributeValue> expectedAtributes = 
       ImmutableMap.<String, ExpectedAttributeValue>builder() 
         .put("date1", date1) 
         .put("date2", date2) 
         .put("date3", date3) 
         .build(); 

     saveExpression.setExpected(expectedAtributes); 
     saveExpression.setConditionalOperator(ConditionalOperator.AND); 

私は両方のシナリオをキャプチャするために保存式を使用する方法がわからないと思います。私は動的に個別の保存式を渡すことができますが、そうすることでクライアントが望ましくない重要なリファクタリングが行われることを認識しています。

答えて

1

存在しないアイテムを条件とし、ConditionalCheckFailedExceptionをキャッチするUpdateItem呼び出しを試してください。 catchブロックでは、アイテムが存在し、既存のアイテムを条件にして上記の条件を満たすUpdateItem呼び出しを実行できることがわかります。 Mapperでattribute_exists conditionsを設定することはできませんので、この機能を利用するにはlow-level APIまたはDocument SDKを使用する必要があります。

try { 
    table.updateItem(new UpdateItemSpec().withPrimaryKey(...) 
     .withConditionExpression("attribute_not_exists(my_hash_key)") 
     //one for each attribute of the item you are creating 
     .withAttributeUpdate(new AttributeUpdate("attribute_name") 
              .put("attribute_value")) 
    ); 
} catch(ConditionalCheckFailedException e) { 
    table.updateItem(new UpdateItemSpec().withPrimaryKey(...) 
     .withConditionExpression("attribute_exists(my_hash_key)") 
     .withUpdateExpression("SET attributeToChange = :val") 
     .withExpressionAttributeValues(ImmutableMap.of(":val", "asdf")) 
    ); 
}