Garry S
Garry S

Reputation: 117

How to get max value from table Dynamodb - Java

How to get max value of field - run_id from DynamoDB table, result will be 3

+--------+----------------------+------------+---------+---------+
| run_id | add_date             | track_name |  status | user_id |
+--------+----------------------+------------+---------+---------+
| 1      | 2022-09-23 11:04:06  | track1     | fail    |  1      |
+--------+----------------------+------------+---------+---------+
| 1      | 2022-09-23 11:04:06  | track2     | pass    |  1      |
+--------+----------------------+------------+---------+---------+
| 1      | 2022-09-23 11:04:06  | track3     | fail    |  1      |
+--------+----------------------+------------+---------+---------+
| 2      | 2022-09-23 11:04:06  | us         | pass    |  2      |
+--------+----------------------+------------+---------+---------+
| 3      | 2022-09-23 11:04:06  | it         | pass    |  3      |
+--------+----------------------+------------+---------+---------+

I know it can be achievable with mysql with "SELECT MAX(run_id) from table_name Limit 1"

Tried below code for get item from table: (its for getting item from table only but i want to see how we can get max using below code)

final AmazonDynamoDB ddb = AmazonDynamoDBClientBuilder.defaultClient();

HashMap<String,AttributeValue> keyToGet = new HashMap<>();
                            
keyToGet.put("run_id", new AttributeValue("3"));
                            
GetItemResult result = ddb.getItem(detail_runinto_table, keyToGet, true);

Upvotes: 0

Views: 164

Answers (2)

Borislav Stoilov
Borislav Stoilov

Reputation: 3697

This is not something easy you can do in NoSQL, at least effectively.

The data in the partition is stored in lexicographical order based on the sort key. This means that if you put the runId as a sort key in a GSI you can query it and get the first element. Just remember that it has to be zero-padded

Upvotes: 1

hunterhacker
hunterhacker

Reputation: 7132

Based on your schema it looks like you're trying to have new data always use the N+1 run_id. Are you sure you want to do that? Why not use a value based on the timestamp? It's like like "3" is any more meaningful than "1666138714" when it comes to unique run IDs.

If you really truly want an incrementing number like that it's best to track the number separately as its own item and maintain that number as you run jobs.

Upvotes: 1

Related Questions