Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
February 21, 2022 03:08 pm GMT

Creating Unique IDs programmatically on DynamoDB

Create a DynamoDB Table

DynamoDB Table

Leave the Partition Key Set To String, this way it will be easier to create Unique Ids Identifiers because unlike MySQL Databases DynamoDB will not generate an auto increment ID. Furthermore, if we select Number or Binaries, there will be a conflict between DynamoDB and the
uuid library because they respectively use different decimal calculation.

Go to the Terminal and create an uuid

Terminal UUID

Copy and paste the uuid, and create the item on the table

Item

Create a put_dynamodb function

put_dynamodb Lambda function

Go to Configuration Permissions, Click on the Role Name and Attach the DynamoDbFullAccess policy to this Role

Role Lambda

Attach Dynamodb Policy To Lambda Role

First check if we can retrieve the data

import jsonimport uuidimport boto3db = boto3.client('dynamodb')def lambda_handler(event, context):    data = db.scan(TableName='database')    return {        'statusCode': 200,        'body': json.dumps('Success')    }

Let's test the function

Test function

Now, let's add a new item and an auto generated id with uuid module, and test the function

import jsonimport uuidimport boto3db = boto3.client('dynamodb')id_db=uuid.uuid4()def lambda_handler(event, context):    data= db.put_item(TableName='database', Item={'id':{'S':str(id_db)},'item':{'S':'iphone-10'},'available':{'BOOL': False}})    return {        'statusCode': 200,        'body': json.dumps('Success')    }

Image description

Let's write the exact same code except that we are going to add a color attribute.

import jsonimport uuidimport boto3db = boto3.client('dynamodb')id_db=uuid.uuid4()def lambda_handler(event, context):    data= db.put_item(TableName='database', Item={'id':{'S':str(id_db)},'item':{'S':'iphone-10'},'available':{'BOOL': False},'color':{'S':'pink'}})    return {        'statusCode': 200,        'body': json.dumps('Success')    }

Now let's check our database

DynamoDb updated

As you can see we haven't entered any id manually, and they have been generated programmatically.


Original Link: https://dev.to/aissalaribi/creating-unique-ids-programmatically-on-dynamodb-486f

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To