如何根据hashkey删除Amazon Dynamodb中的记录?

时间:2013-05-10 20:19:50

标签: c# amazon-dynamodb

我试图通过hashkey从aws dynamodb表中删除所有项目。我在互联网上看到很多关于它的讨论,但没有实际的代码样本,我的所有尝试都失败了。

我在这里做错了什么,或者是否有更好的计划?

List<Document> results = null;
var client = new AmazonDynamoDBClient("myamazonkey", "myamazonsecret");
var table = Table.LoadTable(client, "mytable");

var search = table.Query(new Primitive("hashkey"), new RangeFilter());
do {
results = search.GetNextSet();
search.Matches.Clear();
foreach (var r in results)
                    {
                        client.DeleteItem(new DeleteItemRequest()
                            {
                                Key = new Key() { HashKeyElement = new AttributeValue() { S = "hashkey"}, RangeKeyElement = new AttributeValue() { N = r["range-key"].AsString() } }
                            });
                    }
} while(results.Count > 0);

1 个答案:

答案 0 :(得分:2)

使用AWS批量写入功能解决了问题。我把我砍成25批,但我认为api可能需要100个。

List<Document> results = null;
var client = new AmazonDynamoDBClient("myamazonkey", "myamazonsecret");
var table = Table.LoadTable(client, "mytable");
var batchWrite = table.CreateBatchWrite();
var batchCount = 0;

var search = table.Query(new Primitive("hashkey"), new RangeFilter());
do {
  results = search.GetNextSet();
  search.Matches.Clear();
  foreach (var document in results)
  {
    batchWrite.AddItemToDelete(document);
    batchCount++;
    if (batchCount%25 == 0)
    {
      batchCount = 0;
      try
      {
        batchWrite.Execute();
      }
      catch (Exception exception)
      {
       Console.WriteLine("Encountered an Amazon Exception {0}", exception);
      }

      batchWrite = table.CreateBatchWrite();
     }
   }
   if (batchCount > 0) batchWrite.Execute();
  }
} while(results.Count > 0);