Jojodmo
Jojodmo

Reputation: 23596

Order results in DynamoDB scan

Is it possible to order the results when scanning a DynamoDB table, before getting the data returned to the user?

In SQL, it is possible to run a query like SELECT * FROM posts ORDER BY creationDate DESC. Is it possible to do this with a scan (or with a query, but I don't think that will work, because I do not know the hash key value) in AWS DynamoDB?

Although it is possible to get all of the results from the database, and then sort them, I am expecting for there to be a lot of posts. If there are a lot of posts, then it would take a lot of time, because I would like to load only a certain number of posts until the user decides to load more.

Is there any way to sort the results by a range key, or a local or global secondary index?

I'm trying to find a hack to get around the fact that there seems to be no way to order results, and not looking for something like this:

AWSDynamoDBScanInput.order = NSSortDescriptor(key: "creationDate", ascending: true)

Unless it exists, although from what I've looked at it doesn't seem to be possible.

It looks like the results are sorted by the hash key by default, so, I would like to set the hash key to the item creation date, with a UID for the range key, but the AWS DynamoDB documentation seems to warn against doing this:

Would setting the hash key to creation date:

var creationDate: Int = Int(NSDate().timeIntervalSince1970)

and the range key to a random UID work to sort the posts?

Is it possible to order results when scanning a DynamoDB table? Would setting the creation date (as an Int) as the Hash Key, and a random UID as the Range Key work? Are there any (better) hacks that can be used to get around the fact that DynamoDB does not have a sort function?

Upvotes: 2

Views: 4879

Answers (1)

Max
Max

Reputation: 8836

The only way to do that would be by Querying an Index. You could might have to add a Global Secondary Index to "hack" what you're trying to do but it is probably not a good design. The reason why it needs to be an Index is that Dynamo stores every item in a Hash in order of the Range. So if you had a Hash that you knew (maybe add a property to every document that has the same value and make that the Hash Key) then it would sort by Range (which you'd make the Timestamp that interests you). Then it would be in order. You may run into issues with this, but if, like you say, you're looking for a hack this should work.

Upvotes: 1

Related Questions