How to do it...

Let's discuss the steps to add data items from Lambda without repeating the common steps we already discussed:

  1. Create a Maven project for the Lambda with the common parent and the DynamoDB Java SDK dependency.
  2. Define the Request and Response domain objects.

The Request object for the lambda-dynamodb-put-item lambda is defined as follows:

@Data
public class Request {
private String tableName;
private String partitionKey;
private String sortKey;
private String partitionKeyValue;
private Integer sortKeyValue;
private boolean waitForActive;
private Map<String, String> stringData;
private Map<String, Integer> integerData;
}

I have added two maps, one for string types and one for integer types. The Response object is common to all Lambdas, as discussed in the Using the DynamoDB SDK from Lambda recipe. 

  1. Create the service implementation.

We can add an item into a DynamoDB table as follows:

Table table = dynamoDB.getTable(request.getTableName());

Item item = new Item()
.withPrimaryKey(request.getPartitionKey(), request.getPartitionKeyValue(),
request.getSortKey(), request.getSortKeyValue());

if (request.getStringData() != null) {
request.getStringData().forEach((k, v) -> item.withString(k, v));
}

if (request.getIntegerData() != null) {
request.getIntegerData().forEach((k, v) -> item.withInt(k, v));
}

table.putItem(item);

The complete code is available with the code files. 

  1. Define Lambda handler to call the service method and return a response.
  2. Package and deploy Lambda.
  3. Define the CloudFormation template.

In the CloudFormation template, add permissions for Lambda to put items. If you are waiting for table creation, you also need the DescribeTable permission:

- Effect: Allow
Action:
- dynamodb:PutItem
- dynamodb:DescribeTable
Resource:
- Fn::Sub: arn:aws:dynamodb:${AWS::Region}:${AWS::AccountId}:table/*
  1. Deploy the CloudFormation template.
  2. Invoke Lambda and test it.

We can invoke our Lambda from the CLI as follows:

aws lambda invoke 
--invocation-type RequestResponse
--function-name lambda-dynamodb-put-item
--log-type Tail
--payload '{
"tableName":"my_table",
"partitionKey": "id",
"sortKey": "dateandtime",
"partitionKeyValue": "p1",
"sortKeyValue": 1537963034,
"waitForActive": false,
"stringData" : {
"s1": "v1",
"s2": "v2"
},
"integerData" : {
"i1" : 1,
"i2" : 2
}
}'
--region us-east-1
--profile admin
outputfile.txt

To execute a version 2 service implementation, update the API_VERSION Lambda environment variable to V2:

aws lambda update-function-configuration 
--function-name lambda-dynamodb-put-item
--environment Variables={API_VERSION=V2}
--region us-east-1
--profile admin
  1. Cleanup

You can delete items using aws dynamodb delete-item.

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

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