user3334226
user3334226

Reputation: 151

Maximum value of global secondary index range key in dynamoDB

I have a table in dynamoDB with id as primary key and a global secondary index (GSI). GSI has hash key as p_identifier and range key as financialID. FinancialID is a 6 digit number starting with 100000. I have a requirement to get the maximum of the financialID so that next record to be added can have financialID incremented by 1.

Can anyone help me in making this work? Also is there is any other alternative to do this?

Upvotes: 0

Views: 1752

Answers (3)

Harshal Bulsara
Harshal Bulsara

Reputation: 8274

Firstly, incrementing will not be a good idea for DynamoDB, but the following can be a workaround:

  1. We have to query based on equal-to operator, so let's say:

    p_identifier = 101
    

    and you can use

    scanIndexForward-false
    

    (will sort data descending based on your range key) and get that item and increment your key.

  2. If you don't know p_identifier, then you need to scan (which is not recommended) and manually find largest key and increment.

Upvotes: 0

Sony Kadavan
Sony Kadavan

Reputation: 4072

If you need the FinancialID to be in strict-order, approach by @Chen is good.

On the other hand, if you just need a unique id here, you can use a UUID. Here too there is a very small chance of collision. To counter this, you need to use the API with the "Exists" condition - the call will fail, if it exists and then you can retry with another UUID.

Upvotes: 0

Chen Harel
Chen Harel

Reputation: 10072

I would go and use a different approach.

From your requests I am assuming financialID should be unique. The database won't prevent you from duplicating it and you should make sure some other part of your application syncs these numbers. So you need an atomic counter.

If you must use DynamoDB alone, you should have a table set up just for this type of task. A table where you have a hash primary key called financial_id_counter and you atomically raise it by 1 and use the id retrieved as the next financialID to be used. This is not ideal, but can work when issuing updates with UpdateItem ADD.

Upvotes: 2

Related Questions