Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamodb scan in sorted order

Hi I have a dynamodb table. I want the service to return me all the items in this table and the order is by sorting on one attribute.

Do I need to create a global secondary index for this? If that is the case, what should be the hash key, what is the range key? (Note that query on gsi must specify a "EQ" comparator on the hash key of GSI.)

Thanks a lot!

Erben

like image 873
Erben Mo Avatar asked Feb 15 '14 07:02

Erben Mo


People also ask

How do I sort DynamoDB Scan?

As of now the dynamoDB scan cannot return you sorted results. You need to use a query with a new global secondary index (GSI) with a hashkey and range field. The trick is to use a hashkey which is assigned the same value for all data in your table.

Does DynamoDB support sorting?

DynamoDB uses the partition key as an input to the hash function. The hash function's output decides which partition the item will be placed in, and all items with the same partition key value are stored together. The sort key is used to sort and order items in a partition.

Can you query on sort key DynamoDB?

You can Query any table or secondary index, provided that it has a composite primary key (partition key and sort key). Query operations consume read capacity units, as follows. The table's provisioned read capacity.

How do I sort DynamoDB query results?

Query results are always sorted by the sort key value. If the data type of the sort key is Number, the results are returned in numeric order; otherwise, the results are returned in order of UTF-8 bytes. By default, the sort order is ascending. To reverse the order, set the ScanIndexForward parameter to false.


1 Answers

If you know the HashKey, then any query will return the items sorted by Range key. From the documentation:

Query results are always sorted by the range key. If the data type of the range key is Number, the results are returned in numeric order. Otherwise, the results are returned in order of UTF-8 bytes. By default, the sort order is ascending. To reverse the order, set the ScanIndexForward parameter set to false.

Now, if you need to return all the items, you should use a scan. You cannot order the results of a scan.

Another option is to use a GSI (example). Here, you see that the GSI contains only HashKey. The results I guess will be in sorted order of this key (I didn't check this part in a program yet!).

like image 196
Sony Kadavan Avatar answered Sep 19 '22 18:09

Sony Kadavan