skip to Main Content

Problem: I want to get all items with highest range key.

Example:

id version
test1 3
test1 4
test2 2
test2 3

I expect from query:

id version
test1 4
test2 3

My table is like:

id string -> hash key 
version number -> range key

I’m using guregu and I’m scanning all results to get highest version number.

var results []map[string]interface{}
err := d.table.Scan().All(&results)

What is the best practice to find items with the highest sort key ?

2

Answers


  1. You will need to query instead and by setting ScanIndexForward to false to get it in the reverse order

    Specifies the order for index traversal: If true (default), the traversal is performed in ascending order; if false, the traversal is performed in descending order.
    Items with the same partition key value are stored in sorted order by sort key. If the sort key data type is Number, the results are stored in numeric order. For type String, the results are stored in order of UTF-8 bytes. For type Binary, DynamoDB treats each byte of the binary data as unsigned.
    If ScanIndexForward is true, DynamoDB returns the results in the order in which they are stored (by sort key value). This is the default behavior. If ScanIndexForward is false, DynamoDB reads the results in reverse order by sort key value, and then returns the results to the client.

    Login or Signup to reply.
  2. If you changed your data model slightly where you have a record such as V0 in the below image, you could index sparsely on the latest value allowing you to easily get the the latest version for all items in an efficient manner.

    The alternative is to Scan then Query which is extremely inefficient. So if it’s a frequent lookup pattern, an index is best.

    data

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search