Is it possible to do a conditional put or update in DynamoDB?

Piotr Zurek picture Piotr Zurek · Sep 25, 2015 · Viewed 26.8k times · Source

Let's say that I am storing records with following structure in DynamoDB:

{    
    "id": "57cf5b43-f9ec-4796-9de6-6a50f556cfd8",
    "created_at": "2015-09-18T13:27:00+12:00",
    "count": 3
}

Now, is it possible to achieve the following in one request:

  • if the record with given id doesn't exist it should be created with count = 1
  • if the record for that id exists the counter is being updated.

Currently I'm doing a query to check if the record exist and depending on the result I do a put or an update. It would be nice to fold that into a single operation.

Answer

Piotr Zurek picture Piotr Zurek · Sep 26, 2015

What I didn't mention in my question was that I wanted the count go up for subsequent events without modifying the created_at. My final working UpdateInput looks like that:

{
  Key: {
    id: {
      S: "some_unique_id"
    }
  },
  TableName: "test",
  ExpressionAttributeNames: {
    #t: "created_at",
    #c: "count"
  },
  ExpressionAttributeValues: {
    :t: {
      S: "2015-09-26T15:58:57+12:00"
    },
    :c: {
      N: "1"
    }
  },
  UpdateExpression: "SET #t = if_not_exists(#t, :t) ADD #c :c"
}