user1640256
user1640256

Reputation: 1719

DynamoDB: search on either hash key or range key

I am fairly new to DynamoDB. I have a requirement where I need to design a table to share codes on cellphones. The code details will be stored as attributes. For example:

'A' and 'B' are users '1234567890' and '1234567891' are the recipients. If I make UserId hash key and RecipientNumber as range key, I can find out the recipients with whom the user shared the code. My requirement is to query both ways: 1. Recipients list with whom a user has shared codes(Passing userId in query) 2. List of codes shared with a recipient(by all the users who have shared code with the recipient)

What should be the correct way to design the table?

Upvotes: 0

Views: 1151

Answers (2)

Ivan Mushketyk
Ivan Mushketyk

Reputation: 8305

You need to define your table as this:

User - String - partition key

Recipient - String - range key

and add the following Global Secondary Index:

Recipient - String - GSI partition key

User - String - GSI range key

Regular partition key will allow you to find all recipients for a user, while GSI will allow you to find all users by a recipient.

P.S. You can learn more about DynamoDB design patterns in this video, and specifically about bidirectional queries here.

Upvotes: 1

Dunedan
Dunedan

Reputation: 8465

That's what DynamoDB has Global Secondary Indexes for. They allow you to create an additional projection of your data where the recipients can be the hash key.

Upvotes: 0

Related Questions