Is it possible to run a greater than query in AWS DynamoDB?

Viewed 7360

Let's say I have my DynamoDB table like this, with Order ID as the primary key. :

table screenshot


The Order ID increments by one, everytime I add/put a new item.

Now, I have one number, let's say 1000, and my user wants to get all the items which have Order ID > 1000. So the items returned would be 1001, 1002, 1003, and so on till the last one.


My requirement is as simple as it seems - but is this thing possible to do with Query method of AWS DynamoDB?

Any help is appreciated :) Thanks!

2 Answers

There's currently no way to filter on partition key, but I can suggest a way that you can achieve what you want.

You're heading in the right direction with Query which has a "greater than" operator. However, it only operates on the sort key attribute.

With Query, you essentially choose a single partition key, and provide a filter expression that is applied to the sort key of items within that partition.
Since your partition key is currently "Order ID?", you'll need to add a Global Secondary Index to query the way you want.

Without knowing more about your access patterns, I'd suggest you add a Global Secondary Index using "From" as the partition key, which I assume is the user ID. You can then use "Order ID" as the sort key.

my user wants to get all the items which have Order ID > 1000.

With the GSI in place, you can achieve this by doing a query for items where "User ID" is userId and "Order ID" > orderId.

You can find more on query here, details on adding a GSI here, and more info on choosing a partition key here.

No, because Query expects an exact key, and does not allow an expression for the partition key (it does however for the sort key).

What you could use however is a Scan with a FilterExpressions (see Filter Expressions for Scan and Condition Expressions for the syntax). This reads all records and filters afterwards, so it is not the most effective way.

Related