Reputation: 3382
How can i query a dynamo db sorted by two attributes?
Let’s say for example my entity is github_repository. With the attributes name (S), owner (S), watches (I), stars (I) and forks (I).
(S) - string: (I) - int
And i want to return the top 10 github_repositories by stars and forks. Let’s say if two items have the same stars, i use forks as the tie breaker on the sorting.
Thanks
Upvotes: 0
Views: 467
Reputation: 13781
If you know how you want to sort the (stars, fork) tuple, you can serialize it in an appropriate as a string, and use that as the sort key.
In your case, you said:
I want to return the top 10 github_repositories by stars and forks. Let’s say if two items have the same stars, i use forks as the tie breaker on the sorting.
So if "stars" are numbers 0 through 9, and "forks" (?) are also 0 through 9, you just concatenate the two numbers together to get one string. Or take 10-number if you want reverse sorting (highest stars first). For example, an item with 3 stars and 6 forks will get the string "74". If one item has more stars than another, it will be first in the sort order. If two items have the same stars, then the one with more forks will be first. As you required.
If the meaning of your stars and forks are different, or your sorting requirements are different, the details will be different - but in many cases you can find a way to encode what you want to sort into a single string that DynamoDB can sort lexicographically.
Upvotes: 1
Reputation: 1
You can only sort by one key. For your issue there are two possible solutions I can think of:
Upvotes: 0