Franz See
Franz See

Reputation: 3382

Query Dynamodb with more than one sort keys

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

Answers (2)

Nadav Har'El
Nadav Har'El

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

Erald Calaj
Erald Calaj

Reputation: 1

You can only sort by one key. For your issue there are two possible solutions I can think of:

  • Use a sort key that is a sum of stars and forks (if that suits your use case).
  • Fetch the top ten by starts and then locally use a sort for forks (but that might bring a problem if nr 10 has less forks than nr 11).

Upvotes: 0

Related Questions