scubbo
scubbo

Reputation: 5818

DynamoDB Primary Key strategy

I'm dabbling with DynamoDB (using boto3) for the first time, and I'm not sure how to define my Partition Key. I'm used to SQL, where you can use AUTO_INCREMENT to ensure that the Key will always increase.

I haven't seen such an option in DynamoDB - instead, when using put_item, the "primary key attributes are required" - I take this to mean that I have to define the value explicitly (and, indeed, if I leave it off, I get botocore.exceptions.ClientError: An error occurred (ValidationException) when calling the PutItem operation: One or more parameter values were invalid: Missing the key id in the item)

If already have rows with id 1, 2, 3, ...N, I naturally want the next row that I insert to have Primary Key N+1. But I don't know how to generate that - the solutions given here are all imperfect.

Should I be generating the Primary Key values independently, perhaps by hashing the other values of the item? If I do so, isn't there a (small) chance of hash-collision? Then again, since DynamoDB seems to determine partition based on a hash of the Partition Key, is there any reason for me not to simply use a random sufficiently-long string?

Upvotes: 1

Views: 3102

Answers (2)

Nick
Nick

Reputation: 3845

I had the same problem while working through the Build a basic Web Application tutorial.

In module 4 of the tutorial, after modifying the lambda function to write to the DynamoDB table, I had to change ID to Id in the line marked THIS LINE (see below) after which the test worked.

def lambda_handler(event, context):
# extract values from the event object we got from the Lambda service and store in a variable
    name = event['firstName'] +' '+ event['lastName']
# write name and time to the DynamoDB table using the object we instantiated and save response in a variable
    response = table.put_item(
        Item={
            'ID': name,   <- THIS LINE
            'LatestGreetingTime':now
            })
# return a properly formatted JSON object
    return {
        'statusCode': 200,
        'body': json.dumps('Hello from Lambda, ' + name)
    }

I also had to edit my test input to include a random uuid as shown:

{
  "Id": "560e2227-c738-41d9-ad5a-bcad6a3bc273",
  "firstName": "Ada",
  "lastName": "Lovelace"
}

Upvotes: 0

DanneJ
DanneJ

Reputation: 368

DynamoDb does not support generated keys, you have to specify one yourself. You can't reliably generate sequential IDs.

One common way is instead to use UUIDs.

Upvotes: 4

Related Questions