Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating a unique key for dynamodb within a lambda function

DynamoDB does not have the option to automatically generate a unique key for you.

In examples I see people creating a uid out of a combination of fields, but is there a way to create a unique ID for data which does not have any combination of values that can act as a unique identifier? My questions is specifically aimed at lambda functions.

One option I see is to create a uuid based on the timestamp with a counter at the end, insert it (or check if it exists) and in case of duplication retry with an increment until success. But, this would mean that I could potentially run over the execution time limit of the lambda function without creating an entry.

like image 741
Philiiiiiipp Avatar asked Aug 27 '18 13:08

Philiiiiiipp


People also ask

Can Lambda write to DynamoDB?

AWS Lambda: Allows a Lambda function to access an Amazon DynamoDB table. This example shows how you might create an identity-based policy that allows read and write access to a specific Amazon DynamoDB table. The policy also allows writing log files to CloudWatch Logs.


1 Answers

If you are using Node.js 8.x, you can use uuid module.

var AWS = require('aws-sdk'),
    uuid = require('uuid'),
    documentClient = new AWS.DynamoDB.DocumentClient();
[...]
        Item:{
            "id":uuid.v1(),
            "Name":"MyName"
        },

If you are using Node.js 10.x, you can use awsRequestId without uuid module.

    var AWS = require('aws-sdk'),
        documentClient = new AWS.DynamoDB.DocumentClient();
[...]
    Item:{
        "id":context.awsRequestId,
        "Name":"MyName"
    },
like image 175
hatted Avatar answered Oct 26 '22 07:10

hatted