1

I have a DynamoDB table with two GSI:

GSI 1

  • hash key: studentGroup
  • sort key: mathScore

GSI 2

  • hash key: studentGroup
  • sort key: scienceScore

When I scan the table with filter studentGroup = 1, does DynamoDB return the results in the order of mathScore or scienceScore?

Is there any way to specify which attribute (or which GSI) to be used for sorting?

If not possible, what's the best practice to design GSI to sort by an attribute that the application side can choose?

I tried from the DynamoDB management console, but it seems no way to specify which index to be used for scanning.

Chienwen
  • 11
  • 2
  • 1
    Does this answer your question? [Dynamodb scan in sorted order](https://stackoverflow.com/questions/21794945/dynamodb-scan-in-sorted-order) – Charles Apr 06 '23 at 15:04
  • No @Charles. That question is to create one single GSI to sort by one attribute. But my question is: I already have multiple GSIs and don't know how to specify which index to be used for sorting when scanning. – Chienwen Apr 06 '23 at 16:07
  • @Chienen the top voted answer includes "Now, if you need to return all the items, you should use a scan. You cannot order the results of a scan." – Charles Apr 06 '23 at 22:29

1 Answers1

1

In DynamoDB when you do a Scan there is no order maintained across keys, but only per item collection (items which share the same key).

If you want a result where studentGroup=1 ordered by mathScore then you read from GSI1.

If you want it ordered by scienceScore then read from GSI2.

You must specify which index when you make the request.

aws dynamodb query \
--table-name <TableName> \
--index-name <GSI1 or GSI2> \
--key-condition-expression <>
Leeroy Hannigan
  • 11,409
  • 3
  • 14
  • 31