Generating a unique key for dynamodb within a lambda function

Philiiiiiipp picture Philiiiiiipp · Aug 27, 2018 · Viewed 11.7k times · Source

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.

Answer

hatted picture hatted · Nov 5, 2019

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"
    },