2013-05-10 58 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