Working with items in DynamoDB using the AWS SDK for .NET document model
The following code examples demonstrate how to perform a variety of operations with the AWS SDK for .NET document model. You can use these examples to perform CRUD, batch, and transaction operations.
Topics
To perform data operations using the document model, you must first call the
Table.LoadTable
method, which creates an instance of the
Table
class that represents a specific table. The following C# example
creates a Table
object that represents the ProductCatalog
table in Amazon DynamoDB.
Example
Table table = Table.LoadTable(client, "ProductCatalog");
Note
In general, you use the LoadTable
method once at the beginning of
your application because it makes a DescribeTable
call that adds to the
round trip to DynamoDB.
You can then use the Table
object to perform various data operations.
Each data operation has two types of overloads: One takes the minimum required
parameters and the other takes optional, operation-specific configuration information.
For example, to retrieve an item, you must provide the table's primary key value, in
which case you can use the following GetItem
overload.
Example
// Get the item from a table that has a primary key that is composed of only a partition key. Table.GetItem(Primitive partitionKey); // Get the item from a table whose primary key is composed of both a partition key and sort key. Table.GetItem(Primitive partitionKey, Primitive sortKey);
You also can pass optional parameters to these methods. For example, the preceding
GetItem
returns the entire item including all its attributes. You can
optionally specify a list of attributes to retrieve. In this case, you use the following
GetItem
overload that takes in the operation-specific configuration
object parameter.
Example
// Configuration object that specifies optional parameters. GetItemOperationConfig config = new GetItemOperationConfig() { AttributesToGet = new List<string>() { "Id", "Title" }, }; // Pass in the configuration to the GetItem method. // 1. Table that has only a partition key as primary key. Table.GetItem(Primitive partitionKey, GetItemOperationConfig config); // 2. Table that has both a partition key and a sort key. Table.GetItem(Primitive partitionKey, Primitive sortKey, GetItemOperationConfig config);
You can use the configuration object to specify several optional parameters such as
request a specific list of attributes or specify the page size (number of items per
page). Each data operation method has its own configuration class. For example, you can
use the GetItemOperationConfig
class to provide options for the
GetItem
operation. You can use the PutItemOperationConfig
class to provide optional parameters for the PutItem
operation.
The following sections discuss each of the data operations that are supported by the
Table
class.
Putting an item - Table.PutItem method
The PutItem
method uploads the input Document
instance
to the table. If an item that has a primary key that is specified in the input
Document
exists in the table, the PutItem
operation
replaces the entire existing item. The new item is identical to the
Document
object that you provided to the PutItem
method. If your original item had any extra attributes, they are no longer present
in the new item.
The following are the steps to put a new item into a table using the AWS SDK for .NET document model.
-
Run the
Table.LoadTable
method that provides the table name in which you want to put an item. -
Create a
Document
object that has a list of attribute names and their values. -
Run
Table.PutItem
by providing theDocument
instance as a parameter.
The following C# code example demonstrates the preceding tasks. The example
uploads an item to the ProductCatalog
table.
Example
Table table = Table.LoadTable(client, "ProductCatalog"); var book = new Document(); book["Id"] = 101; book["Title"] = "Book 101 Title"; book["ISBN"] = "11-11-11-11"; book["Authors"] = new List<string> { "Author 1", "Author 2" }; book["InStock"] = new DynamoDBBool(true); book["QuantityOnHand"] = new DynamoDBNull(); table.PutItem(book);
In the preceding example, the Document
instance creates an item that
has Number
, String
, String Set
,
Boolean
, and Null
attributes. (Null
is
used to indicate that the QuantityOnHand for this product is
unknown.) For Boolean
and Null
, use the constructor
methods DynamoDBBool
and DynamoDBNull
.
In DynamoDB, the List
and Map
data types can contain
elements composed of other data types. Here is how to map these data types to the
document model API:
-
List — use the
DynamoDBList
constructor. -
Map — use the
Document
constructor.
You can modify the preceding example to add a List
attribute to the
item. To do this, use a DynamoDBList
constructor, as shown in the
following code example.
Example
Table table = Table.LoadTable(client, "ProductCatalog"); var book = new Document(); book["Id"] = 101; /*other attributes omitted for brevity...*/ var relatedItems = new DynamoDBList(); relatedItems.Add(341); relatedItems.Add(472); relatedItems.Add(649); book.Add("RelatedItems", relatedItems); table.PutItem(book);
To add a Map
attribute to the book, you define another
Document
. The following code example illustrates how to do
this.
Example
Table table = Table.LoadTable(client, "ProductCatalog"); var book = new Document(); book["Id"] = 101; /*other attributes omitted for brevity...*/ var pictures = new Document(); pictures.Add("FrontView", "http://example.com/products/101_front.jpg" ); pictures.Add("RearView", "http://example.com/products/101_rear.jpg" ); book.Add("Pictures", pictures); table.PutItem(book);
These examples are based on the item shown in Referring to item attributes when using
expressions in DynamoDB. The
document model lets you create complex nested attributes, such as the
ProductReviews
attribute shown in the case study.
Specifying optional parameters
You can configure optional parameters for the PutItem
operation by
adding the PutItemOperationConfig
parameter. For a complete list of
optional parameters, see PutItem. The following C# code example puts an item
in the ProductCatalog
table. It specifies the following optional
parameter:
-
The
ConditionalExpression
parameter to make this a conditional put request. The example creates an expression that specifies theISBN
attribute must have a specific value that has to be present in the item that you are replacing.
Example
Table table = Table.LoadTable(client, "ProductCatalog"); var book = new Document(); book["Id"] = 555; book["Title"] = "Book 555 Title"; book["Price"] = "25.00"; book["ISBN"] = "55-55-55-55"; book["Name"] = "Item 1 updated"; book["Authors"] = new List<string> { "Author x", "Author y" }; book["InStock"] = new DynamoDBBool(true); book["QuantityOnHand"] = new DynamoDBNull(); // Create a condition expression for the optional conditional put operation. Expression expr = new Expression(); expr.ExpressionStatement = "ISBN = :val"; expr.ExpressionAttributeValues[":val"] = "55-55-55-55"; PutItemOperationConfig config = new PutItemOperationConfig() { // Optional parameter. ConditionalExpression = expr }; table.PutItem(book, config);
Getting an item - Table.GetItem
The GetItem
operation retrieves an item as a Document
instance. You must provide the primary key of the item that you want to retrieve as
shown in the following C# code example.
Example
Table table = Table.LoadTable(client, "ProductCatalog"); Document document = table.GetItem(101); // Primary key 101.
The GetItem
operation returns all the attributes of the item and performs
an eventually consistent read (see Read consistency) by default.
Specifying optional parameters
You can configure additional options for the GetItem
operation by
adding the GetItemOperationConfig
parameter. For a complete list of
optional parameters, see GetItem. The following C# code example retrieves an
item from the ProductCatalog
table. It specifies the
GetItemOperationConfig
to provide the following optional
parameters:
-
The
AttributesToGet
parameter to retrieve only the specified attributes. -
The
ConsistentRead
parameter to request the latest values for all the specified attributes. To learn more about data consistency, see Read consistency.
Example
Table table = Table.LoadTable(client, "ProductCatalog"); GetItemOperationConfig config = new GetItemOperationConfig() { AttributesToGet = new List<string>() { "Id", "Title", "Authors", "InStock", "QuantityOnHand" }, ConsistentRead = true }; Document doc = table.GetItem(101, config);
When you retrieve an item using the document model API, you can access individual
elements within the Document
object is returned, as shown in the
following example.
Example
int id = doc["Id"].AsInt(); string title = doc["Title"].AsString(); List<string> authors = doc["Authors"].AsListOfString(); bool inStock = doc["InStock"].AsBoolean(); DynamoDBNull quantityOnHand = doc["QuantityOnHand"].AsDynamoDBNull();
For attributes that are of type List
or Map
, here is how
to map these attributes to the document model API:
-
List
— Use theAsDynamoDBList
method. -
Map
— Use theAsDocument
method.
The following code example shows how to retrieve a List
(RelatedItems) and a Map
(Pictures) from the Document
object:
Example
DynamoDBList relatedItems = doc["RelatedItems"].AsDynamoDBList(); Document pictures = doc["Pictures"].AsDocument();
Deleting an item - Table.DeleteItem
The DeleteItem
operation deletes an item from a table. You can pass the
item's primary key as a parameter. Or, if you've already read an item and have the
corresponding Document
object, you can pass it as a parameter to the
DeleteItem
method, as shown in the following C# code example.
Example
Table table = Table.LoadTable(client, "ProductCatalog"); // Retrieve a book (a Document instance) Document document = table.GetItem(111); // 1) Delete using the Document instance. table.DeleteItem(document); // 2) Delete using the primary key. int partitionKey = 222; table.DeleteItem(partitionKey)
Specifying optional parameters
You can configure additional options for the Delete
operation by
adding the DeleteItemOperationConfig
parameter. For a complete list of
optional parameters, see DeleteTable. The following C# code example specifies
the two following optional parameters:
-
The
ConditionalExpression
parameter to ensure that the book item being deleted has a specific value for the ISBN attribute. -
The
ReturnValues
parameter to request that theDelete
method return the item that it deleted.
Example
Table table = Table.LoadTable(client, "ProductCatalog"); int partitionKey = 111; Expression expr = new Expression(); expr.ExpressionStatement = "ISBN = :val"; expr.ExpressionAttributeValues[":val"] = "11-11-11-11"; // Specify optional parameters for Delete operation. DeleteItemOperationConfig config = new DeleteItemOperationConfig { ConditionalExpression = expr, ReturnValues = ReturnValues.AllOldAttributes // This is the only supported value when using the document model. }; // Delete the book. Document d = table.DeleteItem(partitionKey, config);
Updating an item - Table.UpdateItem
The UpdateItem
operation updates an existing item if it is present. If
the item that has the specified primary key is not found, the UpdateItem
operation adds a new item.
You can use the UpdateItem
operation to update existing attribute values,
add new attributes to the existing collection, or delete attributes from the existing
collection. You provide these updates by creating a Document
instance that
describes the updates that you want to perform.
The UpdateItem
action uses the following guidelines:
-
If the item does not exist,
UpdateItem
adds a new item using the primary key that is specified in the input. -
If the item exists,
UpdateItem
applies the updates as follows:-
Replaces the existing attribute values with the values in the update.
-
If an attribute that you provide in the input does not exist, it adds a new attribute to the item.
-
If the input attribute value is null, it deletes the attributes, if it is present.
-
Note
This midlevel UpdateItem
operation does not support the
Add
action (see UpdateItem) that is supported by the
underlying DynamoDB operation.
Note
The PutItem
operation (Putting an item - Table.PutItem method) can also perform an update. If you call
PutItem
to upload an item and the primary key exists, the
PutItem
operation replaces the entire item. If there are attributes
in the existing item and those attributes are not specified on the
Document
that is being put, the PutItem
operation
deletes those attributes. However, UpdateItem
only updates the
specified input attributes. Any other existing attributes of that item remain
unchanged.
The following are the steps to update an item using the AWS SDK for .NET document model:
-
Run the
Table.LoadTable
method by providing the name of the table in which you want to perform the update operation. -
Create a
Document
instance by providing all the updates that you want to perform.To delete an existing attribute, specify the attribute value as null.
-
Call the
Table.UpdateItem
method and provide theDocument
instance as an input parameter.You must provide the primary key either in the
Document
instance or explicitly as a parameter.
The following C# code example demonstrates the preceding tasks. The code example
updates an item in the Book
table. The UpdateItem
operation
updates the existing Authors
attribute, deletes the PageCount
attribute, and adds a new XYZ
attribute. The Document
instance
includes the primary key of the book to update.
Example
Table table = Table.LoadTable(client, "ProductCatalog"); var book = new Document(); // Set the attributes that you wish to update. book["Id"] = 111; // Primary key. // Replace the authors attribute. book["Authors"] = new List<string> { "Author x", "Author y" }; // Add a new attribute. book["XYZ"] = 12345; // Delete the existing PageCount attribute. book["PageCount"] = null; table.Update(book);
Specifying optional parameters
You can configure additional options for the UpdateItem
operation by
adding the UpdateItemOperationConfig
parameter. For a complete list of
optional parameters, see UpdateItem.
The following C# code example updates a book item price to 25. It specifies the two following optional parameters:
-
The
ConditionalExpression
parameter that identifies thePrice
attribute with value20
that you expect to be present. -
The
ReturnValues
parameter to request theUpdateItem
operation to return the item that is updated.
Example
Table table = Table.LoadTable(client, "ProductCatalog"); string partitionKey = "111"; var book = new Document(); book["Id"] = partitionKey; book["Price"] = 25; Expression expr = new Expression(); expr.ExpressionStatement = "Price = :val"; expr.ExpressionAttributeValues[":val"] = "20"; UpdateItemOperationConfig config = new UpdateItemOperationConfig() { ConditionalExpression = expr, ReturnValues = ReturnValues.AllOldAttributes }; Document d1 = table.Update(book, config);
Batch write - putting and deleting multiple items
Batch write refers to putting and deleting multiple items in a batch. The operation enables you to put and delete multiple items from one or more tables in a single call. The following are the steps to put or delete multiple items from a table using the AWS SDK for .NET document model API.
-
Create a
Table
object by executing theTable.LoadTable
method by providing the name of the table in which you want to perform the batch operation. -
Run the
createBatchWrite
method on the table instance you created in the preceding step and create aDocumentBatchWrite
object. -
Use the
DocumentBatchWrite
object methods to specify the documents that you want to upload or delete. -
Call the
DocumentBatchWrite.Execute
method to run the batch operation.When using the document model API, you can specify any number of operations in a batch. However, DynamoDB limits the number of operations in a batch and the total size of the batch in a batch operation. For more information about the specific limits, see BatchWriteItem. If the document model API detects that your batch write request exceeded the number of allowed write requests, or the HTTP payload size of a batch exceeded the limit allowed by
BatchWriteItem
, it breaks the batch into several smaller batches. Additionally, if a response to a batch write returns unprocessed items, the document model API automatically sends another batch request with those unprocessed items.
The following C# code example demonstrates the preceding steps. The example uses batch write operation to perform two writes; upload a book item and delete another book item.
Table productCatalog = Table.LoadTable(client, "ProductCatalog"); var batchWrite = productCatalog.CreateBatchWrite(); var book1 = new Document(); book1["Id"] = 902; book1["Title"] = "My book1 in batch write using .NET document model"; book1["Price"] = 10; book1["Authors"] = new List<string> { "Author 1", "Author 2", "Author 3" }; book1["InStock"] = new DynamoDBBool(true); book1["QuantityOnHand"] = 5; batchWrite.AddDocumentToPut(book1); // specify delete item using overload that takes PK. batchWrite.AddKeyToDelete(12345); batchWrite.Execute();
For a working example, see Example: Batch operations using the AWS SDK for .NET document model API.
You can use the batchWrite
operation to perform put and delete operations
on multiple tables. The following are the steps to put or delete multiple items from
multiple tables using the AWS SDK for .NET document model.
-
You create a
DocumentBatchWrite
instance for each table in which you want to put or delete multiple items, as described in the preceding procedure. -
Create an instance of the
MultiTableDocumentBatchWrite
and add the individualDocumentBatchWrite
objects to it. -
Run the
MultiTableDocumentBatchWrite.Execute
method.
The following C# code example demonstrates the preceding steps. The example uses the batch write operation to perform the following write operations:
-
Put a new item in the
Forum
table item. -
Put an item in the
Thread
table and delete an item from the same table.
// 1. Specify item to add in the Forum table. Table forum = Table.LoadTable(client, "Forum"); var forumBatchWrite = forum.CreateBatchWrite(); var forum1 = new Document(); forum1["Name"] = "Test BatchWrite Forum"; forum1["Threads"] = 0; forumBatchWrite.AddDocumentToPut(forum1); // 2a. Specify item to add in the Thread table. Table thread = Table.LoadTable(client, "Thread"); var threadBatchWrite = thread.CreateBatchWrite(); var thread1 = new Document(); thread1["ForumName"] = "Amazon S3 forum"; thread1["Subject"] = "My sample question"; thread1["Message"] = "Message text"; thread1["KeywordTags"] = new List<string>{ "Amazon S3", "Bucket" }; threadBatchWrite.AddDocumentToPut(thread1); // 2b. Specify item to delete from the Thread table. threadBatchWrite.AddKeyToDelete("someForumName", "someSubject"); // 3. Create multi-table batch. var superBatch = new MultiTableDocumentBatchWrite(); superBatch.AddBatch(forumBatchWrite); superBatch.AddBatch(threadBatchWrite); superBatch.Execute();