dimanche 5 juillet 2015

Perform INSERT OR UPDATE as a single operation with DynamoDB

We are using DynamoDB for counting user actions and an item must be either inserted or updated, depending on whatever it's already exists. The code must also update a counter. Right now we do this with 2 steps:

using (var client = AWSClientFactory.CreateAmazonDynamoDBClient(RegionEndpoint.USEast1))
{
    var table = Table.LoadTable(client, TableName);
    var item = await table.GetItemAsync(id);
    if (item == null)
    {
        // row not exists -> insert & return 1
        var document = new Document();
        document["Id"] = id;
        document["Counter"] = 1;
        await table.PutItemAsync(document);
        return 1;
    }
    // row exists -> increment counter & update
    var counter = item["Counter"].AsInt();
    item["Counter"] = counter + 1;
    await table.UpdateItemAsync(item);
    return counter + 1;
}

The problem with the code is that it increases latency times & server load. I would prefer to do this with a single operation. I think this should be possible with conditional expressions but I cannot figure out how to do this using .NET SDK.




Aucun commentaire:

Enregistrer un commentaire