DynamoDB - 使用批处理操作覆盖HashKey

时间:2015-07-28 13:18:38

标签: java amazon-web-services amazon-dynamodb

我有一个DynamoDB,我用它来存储有关EC2实例的一些信息,所以我使用实例id作为HashKey。

每周一次,我运行的代码会在此表中插入大量记录:

AmazonDynamoDB amazonDynamoDB = new AmazonDynamoDBClient();
DynamoDBMapper mapper = new DynamoDBMapper(amazonDynamoDB);

// saving records
List<FailedBatch> failedBatch = mapper.batchSave(recordsToSave);

我只关心最新信息,所以如果我试图插入的HashKey已经存在于数据库中,我想覆盖DynamoDB中的旧记录。但是,每次我尝试插入这样的值时,操作都会失败(failedBatch),因为它无法处理重复。

有没有办法如何使用DynamoDB实现此行为,还是必须更改表设计?

1 个答案:

答案 0 :(得分:1)

Batch operations cannot update items. See:

http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_BatchWriteItem.html

BatchWriteItem cannot update items. To update items, use the UpdateItem API.

What I would do is:

  • attempt to do the batch write
  • look at failures that come back
  • batch get the failed items and batch write them to a temp table
  • batch write delete all the items that were failed (already existing)
  • batch write the failures again to main table
  • purge all items from temp table

As an alternative you can use the UpdateItem api but that's probably going to be slower.