I have a nodejs lambda function with three dynamodb tables associated via trigger. I am indexing the records to elasticsearch based on the event fired using the lambda function code. Basically, I need to find out the table name in which the records were inserted or atleast need to identify the trigger which has been executed among the three. This is needed so that the elasticsearch index type names can be varied while indexing.
3 Answers
Schema of the DynamoDB streams event sent to Lambda contains Streams Arn. Here is the sample lambda documented.
We can extract table name from eventSourceARN. In this example it is BarkTable
{
"Records": [
{
"eventID": "7de3041dd709b024af6f29e4fa13d34c",
"eventName": "INSERT",
"eventVersion": "1.1",
"eventSource": "aws:dynamodb",
"awsRegion": "us-west-2",
"dynamodb": {
"ApproximateCreationDateTime": 1479499740,
"Keys": {
"Timestamp": {
"S": "2016-11-18:12:09:36"
},
"Username": {
"S": "John Doe"
}
},
"NewImage": {
"Timestamp": {
"S": "2016-11-18:12:09:36"
},
"Message": {
"S": "This is a bark from the Woofer social network"
},
"Username": {
"S": "John Doe"
}
},
"SequenceNumber": "13021600000000001596893679",
"SizeBytes": 112,
"StreamViewType": "NEW_IMAGE"
},
"eventSourceARN": "arn:aws:dynamodb:us-east-1:123456789012:table/BarkTable/stream/2016-11-16T20:42:48.104"
}
]
}
Comments
I found another workaround to determine the table. An array of table names was declared and checked whether the table name text from array exists in the arn and set the same value to variable. An example code-snippet is below
var tables = ["table1", "table2"];
module.exports.es = async(event, context) => {
for (var i = 0; i < event.Records.length; i++) {
const record = event.Records[i];
const arnText = record.eventSourceARN;
var indexName, x;
for(x of tables) {
if(arnText.includes(x)) {
indexName = x;
break;
}
}
....
}
The variable indexName consists of the table name
Thanks
Comments
You can set an environmental variable containing the ARN of the table sending the event - and check it against the eventSourceARN attribute from an incoming event Record.
In a Serverless app, for example, if you have a table named ProfilesTable, you can add the following to your trigger to get the full table StreamArn:
environment:
PROFILES_STREAM_ARN: !GetAtt [ProfilesTable, StreamArn]
Then, you'd just access the Arn in your trigger Lambda:
const profilesStreamArn = process.env.PROFILES_STREAM_ARN
When you want to compare:
profilesStreamArn === event.Records[n].eventSourceARN
Hope this helps.