Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create multiple DynamoDB entries under the same primary key?

I am developing a skill for Amazon Alexa and I'm using DynamoDB for storing information about the users favorite objects. I would like 3 columns in the database:

  1. Alexa userId
  2. Object
  3. Color

I currently have the Alexa userId as the primary key. The problem that I am running into is that if I try to add an entry into the db with the same userId, it overwrites the entry already in there. How can I allow a user to have multiple objects associated with them in the db by having multiple rows? I want to be able to query the db by the userId and receive all the objects that they have specified.

If I create a unique id for every entry, and there are multiple users, I can't possibly know the id to query by to get the active users' objects.

like image 463
LucasN Avatar asked Jul 21 '17 01:07

LucasN


1 Answers

You have two main options here, and they have different pros and cons

First you can use a composite primary key. It allows you to have 1-to-N relationships in your table.

In your case it can be something like:

AlexaId - partition key

Object - sort key

It allows you to get all objects for a given AlexaId.

Limitations of this method:

  • You can store up to 10GB of data with the same partition key, it means that sum of sizes of all items for the the same AlexaId is limited by 10GB.

  • Working with multiple items in this way is not atomic. DynamoDB does not natively supports transactions, so you can't have atomicity when you work with items. You can use DynamoDB transactions library for Java, but transactions are quite expensive in DynamoDB.

Another option is to store these objects in an item itself. While in a regular SQL database you can only store scalar values in a row in DynamoDB every item can contain complex types, such as sets, lists, and nested objects.

You can read more about DynamoDB data types here.

With this you can have a table like this:

AlexaId - partition key

Objects - a list or set or a map

Pros of this method:

  • DynamoDB natively supports atomicity per item. You can perform atomic updates of an item and even have optimistic locking

Limitations of this method:

  • An item size is limited by 400KB, so you can't store a lot of data in it.
like image 98
Ivan Mushketyk Avatar answered Sep 20 '22 10:09

Ivan Mushketyk