Java DynamoDB - 仅在密钥尚未存在时插入(无映射器)

Jer*_*emy 8 java amazon-dynamodb

如果密钥不存在,我只想插入此行.如果密钥已存在,我不想覆盖该行.

我的语法是这样的:

new PutItemRequest().withTableName(myTableName).withItem(myItem).withConditionExpression(?)
Run Code Online (Sandbox Code Playgroud)

根据AWS文档,我会使用属性ATTRIBUTE_NOT_EXISTS.我也可以使用ComparisonOperator.NULL等.据我所知.

语法提示?这个withConditionExpression机制的一些解释?

zap*_*apl 6

doc说ConditionExpression取代了legacy ConditionalOperator(.NULL).你可以去两条路线,但你应该使用.withConditionExpression(...)而不是操作数路线.

对于更复杂的表达式,还有https://java.awsblog.com/post/TxBG87QOQZRZJF/DynamoDB-XSpec-API.

但在你的情况下,它应该通过写作

.withConditionExpression("attribute_not_exists(thingId)")
Run Code Online (Sandbox Code Playgroud)

假设您的哈希键属性已命名thingId.这种方法也记录在这里:http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_PutItem.html

要防止新项替换现有项,请使用包含attribute_not_exists函数的条件表达式,该函数的名称将用作表的HASH键.由于每条记录都必须包含该属性,因此只有在不存在匹配项的情况下,attribute_not_exists函数才会成功.


Sin*_*dhu 5

我们可以将Dynamo Db主键定义为(分区键和排序键)的组合。基于此假设,此代码将丢弃重复的记录。

PrimaryKey primaryKey = new PrimaryKey();
primaryKey.addComponent("Partition_Key", partitionId);
primaryKey.addComponent("Sort_Key",sortId);

    Item item = new Item().withPrimaryKey(primaryKey).withString("username", userName).withLong("time", time);

    try {

        PutItemSpec putItemSpec = new PutItemSpec().withItem(item).withConditionExpression("attribute_not_exists(Sort_Key)");
        table.putItem(putItemSpec);

    } catch(ConditionalCheckFailedException ex) {
         logger.error("Record already exists in Dynamo DB Table ");

    }
Run Code Online (Sandbox Code Playgroud)