Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DynamoDB - Multiple range keys

Can we have more than 2 fields as primary key in DynamoDB.

Or can i create local secondary index for each field that i want to be a range key and build a query with multiple range keys simultaneously?

like image 884
user307524 Avatar asked Oct 16 '25 04:10

user307524


2 Answers

Given the specifics you stated I believe what you need is a GSI with a composite index. Your table would look something like this:

Partition Key        GSI Partition          GSI Sort
ID                   ID                     Type+Timestamp

With this you can query the GSI with a filter expression like this:

#pk = :pk AND begins_with(#sk, :type)

Your ExpressionAttributeNames would need to map #pk to the ID field, and #sk to the name of the composite field.

Your ExpressionAttributeValues would need to map :type to the value you're searching for ("Read" or "Unread").

Because you are filtering on the type (the first part of the sort key) the first part of the sort key will always be the same, so the timestamp will be used for the ordering of the results.

like image 134
Jason Wadsworth Avatar answered Oct 18 '25 03:10

Jason Wadsworth


You can only have 2 fields as a primary key in DynamoDB. If you want multiple different range keys you can make a local secondary index for each one but you can still only query 1 index at a time. You can also only put 5 LSIs on a table.

What is the data you are trying to model? What are the query patterns that you need to support?

like image 28
Brian Winant Avatar answered Oct 18 '25 02:10

Brian Winant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!