Reputation: 63
I am learning how to model a NoSQL databases and trying to understand how to make this works properly.
For my use case I have spin up a local instance of aws dynamo db and connected successfully.
Now, let's say I have two contexts "Users" and "Groups", where one user can belong to any group, and one group can have multiple users. I am trying to avoid multiple collections but I cannot see the way to.
What I have in mind is something like:
{
name: "Bob Smith",
dob: "1980-01-01
groups: [
{
name: "Sports"
CreatedAt: "2022-01-05"
}.
{
name: "Arts"
CreatedAt: "2022-01-08"
}
]
}
What I am not sure is what should we do if I need to create or update a Group? if I follow the previous pattern, how would be the query for the groups?
Shall I have 2 collections?
Thanks guys for your advice.
Upvotes: 0
Views: 574
Reputation: 19893
You would typically only hold a pointer to the groups within a users item, if you need to update the group details then you would do so in the item for the group.
pk | sk | groups | other |
---|---|---|---|
user123 | USER#user123 | groups[{pk:group1, sk: GROUP#group1}, {pk:group3, sk: GROUP#group3}] | user data |
user009 | USER#user009 | groups[{pk:group5, sk: GROUP#group5}, {pk:group7, sk: GROUP#group7}] | user data |
group1 | GROUP#group1 | group-info thats editable | |
group3 | GROUP#group3 | group-info thats editable | |
group5 | GROUP#group5 | group-info thats editable | |
group7 | GROUP#group7 | group-info thats editable |
Of course this is not the only way to do this, but with all things NoSQL it totally depends on your access patterns. For example, if you have a requirement to get all users for a given group then you would need to change the above schema:
pk | sk | other | other |
---|---|---|---|
user123 | USER#user123 | user-data | |
user123 | GROUP#group1 | some data | |
user123 | GROUP#group3 | some data | |
group1 | GROUP#group1 | group data | |
group3 | GROUP#group3 | group data |
Now you can get all the groups a user belongs to by issuing a Query
stating:
pk=user123 AND sk BEGINS_WITH(GROUP#)
.
Then use a Global Secondary Index to get all the users which belong to a given group, with sk
being your GSI's partition key:
gsi_pk = GROUP#group1
Upvotes: 1