Interacting using the SDK

Switching tack a bit, let's talk about how we can programmatically add data into our new table from a Lambda function (or any other compute provider using an SDK). We'll step through the methods that are required to insert and query the data in a table. To get a good range of implementations, we'll give examples for Python, Node.js, Java, and C#. Like any other function, while using the SDK, we need to make sure we have it imported. For these examples, I'm going to assume we have imported it already and set our region correctly.

The first language to cover is Node.js. Here's how to insert a single item and then retrieve that same item. Notice that the number values are strings, but the Boolean value is not. The code following has a params object to set up the payload, and then uses the putItem API action from the AWS SDK for DynamoDB:

let ddb = new AWS.DynamoDB({apiVersion: '2012-08-10'});

let params = {
TableName: 'photos-metadata',
Item: {
'PHOTO_ID': { N: '1' }
'FILENAME': { S: 'myphoto.jpg' }
'FOCAL_LENGTH' : { N: '25' },
'ISO_SPEED' : { N: '200' }
'CAMERA_MAKE': { S: 'Olympus' }
'FLASH_FIRED': { BOOL: false }
}
};

ddb.putItem(params, (err, data) => {
if (err) {
console.log("Error", err);
} else {
console.log("Success", data);
}
});

Assuming all is going well, we will have that item inserted into our photos-metadata table. To get this item, we can use the getItem method and identify the item using our primary key. Alternatively, we can query for the data if we think there might be more than one item being returned.

Here's a simple call to get our existing item:

let ddb = new AWS.DynamoDB({apiVersion: '2012-08-10'});

let params = {
TableName: 'photos-metadata',
Key: {
'PHOTO_ID': { N: '1' }
}
};

ddb.getItem(params, (err, data) => {
if (err) console.log("Error", err);
else console.log("Success", data.Item);
});

This will retrieve all the values for the item. To filter this down, we could use the ProjectionExpression parameter to get only the value we need. This will help you optimize your usage of DynamoDB.

The same scenario in Python is much the same:

dynamodb = boto3.client('dynamodb')

dynamodb.put_item(
TableName='photos-metadata',
Item={
'PHOTO_ID': { 'N':'1' },
'FILENAME': { 'S':'myphoto.jpg' },
'FOCAL_LENGTH' : { 'N': '25' },
'ISO_SPEED' : { 'N': '200' },
'CAMERA_MAKE': { 'S': 'Olympus' },
'FLASH_FIRED': { 'BOOL': false }
}
)

You can also pull the table name out and set that as an object:

dynamodb = boto3.client('dynamodb')
table = dynamodb.Table('photos-metadata')

response = table.get_item(
Item = {
'PHOTO_ID': '1'
}
)

return response['Item']

The Java example has lots of imports that I've left out for brevity:

final AmazonDynamoDB ddb = AmazonDynamoDBClientBuilder.defaultClient();
PutItemRequest request = new PutItemRequest();
request.setTableName("photos-metadata");

Map<String, AttributeValue> map = new HashMap<>();
map.put("PHOTO_ID", new AttributeValue().withN("1"));
...
map.put("FLASH_FIRED", new AttributeValue().withBOOL(false);

request.setItem(map);
try {
PutItemResult result = ddb.putItem(request);
} catch (AmazonServiceException e) {
System.out.println(e.getErrorMessage());
}

To get an item using Java, we need to use the following code: 

private static void retrieveItem() {
    Table table = dynamoDB.getTable(tableName);
    try {
        Item item = table.getItem("ID", 303, "ID, Nomenclature, Manufacturers", null);
        System.out.println("Displaying retrieved items...");
        System.out.println(item.toJSONPretty());
    } catch (Exception e) {
        System.err.println("Cannot retrieve items.");
        System.err.println(e.getMessage());
    }
}

Finally, let's look at the .NET examples. The following code uses the Amazon.DynamoDBv2 namespace:

var client = new AmazonDynamoDBClient();

var request1 = new PutItemRequest
{
TableName = "photos-metadata",
Item = new Dictionary<string, AttributeValue>
{
{ "PHOTO_ID", new AttributeValue { N = "1" }},
{ "FILENAME", new AttributeValue { S = "myphoto.jpg" }},
...
{ "CAMERA_MAKE", new AttributeValue { S = "Olympus" }},
{ "FLASH_FIRED", new AttributeValue { BOOL = new DynamoDBBool(false) }}
}
};

client.PutItem(request1);

Getting two attributes of the item, while specifying that we want read consistency, can be done with the following code:

private static AmazonDynamoDBClient client = new AmazonDynamoDBClient();
Table photosMetadata = Table.LoadTable(client, "photos-metadata");

private static void RetrieveItem(Table photosMetadata)
{
{
AttributesToGet = new List<string> { "PHOTO_ID", "FILENAME" },
ConsistentRead = true
};
Document document = productCatalog.GetItem("1");
PrintDocument(document);
}

The preceding code snippets are examples of how we can put and get items in a DynamoDB table. There are plenty of other operations we can do via the SDK as well. For now, you have learned enough of the basics to get started. Consult the documentation to find out more about the available options. 

The next section introduces another service that can help take your serverless application development to the next level. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.12.3