forked from aws-samples/aws-dynamodb-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBatchWriteItem.cs
94 lines (84 loc) · 3.92 KB
/
BatchWriteItem.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
using System;
using System.Threading.Tasks;
using Amazon;
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.Model;
using System.Collections.Generic;
namespace DotnetSamples.WorkingWithItems
{
public class BatchWriteItem
{
/// <summary>
/// Example that writes to a DynamoDb more than one item in one call.
/// </summary>
/// <returns></returns>
public static async Task BatchWriteExampleAsync()
{
//Create Client
var client = new AmazonDynamoDBClient(RegionEndpoint.USWest2);
//Definition of the first item to put on a table
var putFirstItem = new PutRequest(new Dictionary<string, AttributeValue>
{
{"pk", new AttributeValue("[email protected]")},
{"sk", new AttributeValue("metadata")},
{"attribute1",new AttributeValue("Attribute1 value") }
//Add other attributes as you need
}
);
//Definition of the second item to put on a table
var putSecondItem = new PutRequest(new Dictionary<string, AttributeValue>
{
{"pk", new AttributeValue("[email protected]")},
{"sk", new AttributeValue("metadata")},
{"attribute1",new AttributeValue("Attribute1 value") }
//Add other attributes as you need
}
);
//Definition of an item to delete
var deleteItem = new DeleteRequest(new Dictionary<string, AttributeValue>
{
{"pk", new AttributeValue("[email protected]")},
{"sk", new AttributeValue("metadata")},
}
);
//Request that group all the previous Put & Delete actions
var writeRequest = new BatchWriteItemRequest
{
RequestItems = new Dictionary<string, List<WriteRequest>>
{
{
//Name of the table
"RetailDatabase",
new List<WriteRequest>()
{
new WriteRequest(putFirstItem),
new WriteRequest(putSecondItem),
new WriteRequest(deleteItem)
}
},//You can execute other collections of requests on other tables at the same time
{
//Name of the table
"RetailDatabase2",
new List<WriteRequest>()
{
new WriteRequest(putFirstItem),
new WriteRequest(putSecondItem),
new WriteRequest(deleteItem)
}
}
}
};
try
{
//Execution of the request
var responseWrite = await client.BatchWriteItemAsync(writeRequest);
Console.WriteLine($"Status {responseWrite.HttpStatusCode}");
Console.WriteLine($"Number of items not processed that you need to try again:{responseWrite.UnprocessedItems}");
}
catch (Exception e)
{
Console.Error.WriteLine(e.Message);
}
}
}
}