2013-05-10 52 views
2

我想通过hashkey从aws dynamodb表中删除所有项目。我在互联网上看到很多关于它的讨论,但没有实际的代码示例,我所有的尝试都失败了。如何根据hashkey删除Amazon 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); 

回答

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); 
+0

你能确认API可能能够取100个项目吗?根据[这些文档](http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_BatchWriteItem.html)我相信它只能像你的代码示例一样做25。 – 2015-02-10 13:37:50

+0

是的,看起来get会允许100,但写入被限制为25。 – brendan 2015-03-24 14:35:20