简体   繁体   中英

dynamodb: How to add auto increment numbers to key field while adding record to table

I would like to add auto numbers to key field of table in dynamodb via console, eg 0,1,2,...

I have contact_us table that I would like to have column with auto id increment. Please help me with this.

import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAutoGeneratedKey;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey;
import com.amazonaws.services.dynamodbv2.model.AttributeValue;

public class ContactUs extends HttpServlet {

    String con_id;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try{
           // ...
           // ...

           Map<String, AttributeValue> item = newRecord();
           //System.out.println(item);

           // ...

           dbObject.addRecord(item, "contact_us");

        }catch (Exception e) {
           // TODO: handle exception
           e.printStackTrace();
        }
    }

    private Map<String, AttributeValue> newRecord() {
        Map<String, AttributeValue> item = new HashMap<String, AttributeValue>();
        con_id = getConID();
        dateTimeTimestamp = new SysDateTimeTimestamp();
        //Need to add con_id which will be auto id.
        item.put("con_id", new AttributeValue(con_id));
        // ...
        // ...

        return item;
    }

    @DynamoDBHashKey(attributeName = "con_id")
    @DynamoDBAutoGeneratedKey
    public String getConID(){
       return con_id;
    }

    public void setConID(String con_id){
       this.con_id = con_id;
    }
}

Here I am receiving con_id value blank.

Please refer this link . As per the best practices in DynamoDB, it is not recommended to have an integer which increments by 1 to generate hash key of the table. In order for the table to scale according to the provisioned capacity, requests should spread evenly across the key space.

The recommended approach is to use UUID . If you are using AWS Java SDK, you can use the @DynamoDBAutoGeneratedKey to generate the hash key automatically. The hash key should be defined as string. The key will be generated as standard UUID format which will help to scale and spread the data across the key space.

Sample class with @DynamoDBAutoGeneratedKey:-

import java.io.Serializable;

import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAutoGeneratedKey;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable;

@DynamoDBTable(tableName = "Order")
public class Order implements Serializable {

    private static final long serialVersionUID = -3534650012619938612L;

    private String orderId;

    private String productName;

    @DynamoDBHashKey(attributeName = "orderId")
    @DynamoDBAutoGeneratedKey
    public String getOrderId() {
        return orderId;
    }

    public void setOrderId(String orderId) {
        this.orderId = orderId;
    }

    @DynamoDBAttribute(attributeName = "productName")
    public String getProductName() {
        return productName;
    }

    public void setProductName(String productName) {
        this.productName = productName;
    }

}

Create order method:-

public Boolean createOrder(String productName) {

        DynamoDBMapper dynamoDBMapper = new DynamoDBMapper(dynamoDBClient);

        Order order = new Order();
        order.setProductName(productName);

        dynamoDBMapper.save(order);


        return true;

    }

I have my dynamoDBClient configured using Spring.

@Autowired
private AmazonDynamoDBClient dynamoDBClient;

This code has been tested successfully. It should work if you have the dynamoDBClient configured correctly.

You might be able to use AtomicCounters

This is a quote from the official doc on AtomicCounter

you can use the UpdateItem operation to implement an atomic counter—a numeric attribute that is incremented, unconditionally, without interfering with other write requests. (All write requests are applied in the order in which they were received.) With an atomic counter, the updates are not idempotent. In other words, the numeric value increments each time you call UpdateItem.

You might use an atomic counter to track the number of visitors to a website. In this case, your application would increment a numeric value, regardless of its current value. If an UpdateItem operation fails, the application could simply retry the operation. This would risk updating the counter twice, but you could probably tolerate a slight overcounting or undercounting of website visitors.

That being said, recommended approach is using UUID rather than auto-incremented Integer as you might constraint yourself in performance

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM