简体   繁体   中英

How to model many-to-many through relationships in DynamoDB?

I've read a lot of guides / best practices on how to model many-to-many relationship in DynamoDB single-table design, but I could not find a practical, hands-on guide on how to model a many-to-many "through" relationship.

Specifically, let's say that I got 3 entities: Employees, Teams and Rules

Relationships-wise, we assume that:

- Employees must follow many Rules that are specific for each employee (one-to-many).
- Teams must follow many Rules (many-to-many).
- Employees can be part of different Teams (many-to-many).

My main access pattern would be Get all the Rules that an Employee should follow , that means getting his specific rules as well as the rules he inherited by the Teams he's part of.

I started modelling the table structure like this:

PK SK Attributes...
EMPLOYEE#one METADATA
EMPLOYEE#one RULE#one
EMPLOYEE#one RULE#two
TEAM#one RULE#three
TEAM#one RULE#four

With the idea of using reverse indexing to create the GSIs I needed to cope with my access patterns, But I hit a wall..

How can I model my data (single-table design) to efficiently retrieve all the rules that an Employee should follow?

I think I'd need to move the relationship between Employee and Teams on PK and SK, something like:

PK SK Attributes...
...
EMPLOYEE#one TEAM#one
...

But then I don't know how I could be able to build the correct indexes to retrieve all the infos I need..

The Amazon DynamoDB documentation describes Many-to-Many Relationships here:

https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/bp-adjacency-graphs.html

I ended up creating a composite Key con the SK that includes both Rules applied to Employees and Rules that are bonded to Teams. The final result is something like:

PK SK
#EMPLOYEE_1 #RULE_5
#EMPLOYEE_1 #TEAM_4#RULE_12
#EMPLOYEE_1 #TEAM_4#RULE_13

This should satisfy my access patterns.

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