简体   繁体   中英

How to model many to many relationship in dynamoDB

I have a user object that looks like this:

UserId: UUID;
Watching: Card[];
Stocks: Stock [];
Listing: Card[];

And then I have a Card object that looks like this:

CardId: UUID;
UserId: UUID;
… other card attributes i.e name

And a stock Object that looks like this:

CardId: UUID;
UserId: UUID;
Price: string;
Quantity: string;
Timestamp: string;

My access patterns look like:

  • Get a list of cards belonging to user
  • Get a list of cards a user is watching
  • Get a list of stocks a user owns

The first access pattern is straight forward as it would just be a PK of CardId and SK of UserId

But I am unsure on my second - usually in relational databases I would add a watching Table. And I was thinking I could create a watching entity with a userId and CardId And then have a GSI to get the card related to that watching item but this doesn't feel right to me following single table design.

This is similar to my third access pattern, I have created a separate entity as a stock has different information to a card but they all feel similar.

Is there a better way to model a many to many relationship like this such as having a PK of CardId and SK of UserId . But with different items coming back?

Any help with this would be great! Thanks :)

All your access patterns are based on user-id, which hints that you want the user-id to be the primary key for all the tables (cards, stocks...). It can also be a good security mechanism to make sure that nobody can access the information of other users.

The main "trick" should be on the stocks table as you might have a lot of duplications on the combinations of cards (companies) and stocks if a user can buy and sell different cards and stocks over time. This stocks table can have the following structure:

user-id (primary key)
timestamp (sort key)
card
stock
price

On this table, you can define a couple of indexes (GSI or LSI) for user-card and user-stock

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM