Create Operation - DynamoDB CRUD Operations
Syntax
The syntax for creating an item in DynamoDB using the AWS SDK for JavaScript is as follows:
var params = {
TableName: 'TABLE_NAME',
Item: {
'ATTRIBUTE_NAME_1': { DataType: 'STRING', 'STRING_VALUE': 'ATTRIBUTE_VALUE_1' },
'ATTRIBUTE_NAME_2': { DataType: 'NUMBER', 'NUMBER_VALUE': 'ATTRIBUTE_VALUE_2' }
}
};
docClient.put(params, function(err, data) {
if (err) {
console.log('Error:', err);
} else {
console.log('Item created successfully:', data);
}
});
Example
var AWS = require('aws-sdk');
var docClient = new AWS.DynamoDB.DocumentClient();
var params = {
TableName: 'Table',
Item: {
'item_id': '1234',
'item_name': 'Example Item',
'price': '99.99',
'quantity': '10'
}
};
docClient.put(params, function(err, data) {
if (err) {
console.log('Error:', err);
} else {
console.log('Item created successfully:', data);
}
});
Output
Upon successful execution of the create operation, the response will be a JSON object containing the details of the newly created item.
{
"ConsumedCapacity": null,
"ItemCollectionMetrics": null,
"ResponseMetadata": {
"RequestId": "abc123",
"HTTPStatusCode": 200,
"HTTPHeaders": {
"content-type": "application/x-amz-json-1.0",
"date": "Tue, 17 Aug 2021 15:23:44 GMT",
"x-amzn-requestid": "abc123",
"content-length": "2",
"connection": "keep-alive"
},
"RetryAttempts": 0
}
}
Explanation
The create operation in DynamoDB is used to create a new item in a table. The put
method of the DocumentClient is used to execute the create operation. The params
object contains the details of the table name and the attributes of the new item, where each attribute is defined as a key-value pair in the Item
property of the params
object. In the example above, the new item has attributes item_id
, item_name
, price
, and quantity
.
Use
The create operation in DynamoDB is an essential component of any application which requires persistent storage of structured data. It can be used for a variety of applications, including e-commerce websites for storing product details, social media platforms for storing user information, and messaging applications for storing message data.
Important Points
- Every item in a DynamoDB table must have a unique partition key, which is the primary key for the table, and may also have a sort key.
- The
put
method in the DocumentClient is the preferred method for executing a create operation in DynamoDB. - If an item with the same primary key already exists in the table, the create operation will overwrite the existing item.
Summary
In summary, the create operation in DynamoDB is a simple method for adding a new item in a table. It involves the use of the put
method of the AWS SDK for JavaScript, with the details of the new item provided in the params
object. The create operation is an essential component of any application which requires persistent storage of structured data.