Clojure and DynamoDB with Faraday, Part 4
Ricardo J. Méndez
January 13, 2016
Update and friends
This is the final part of the series where I convert Amazon's Getting Started to Clojure with Faraday. If you've just arrived, the previous parts were:
- Basic table operations and writing data
- Getting querying and scanning
- Working with secondary indexes
This part will correspond to steps 7 and 8 of the Getting Started guide. Let's move on to updating and deleting data!
Update an item
Up date allows us to modify an item's attributes, add new ones, or remove existing attributes. We'll use update expressions, which have the same restrictions as the expressions we saw on part 2.
We also can specify which values we want returned after the update:
- :all-old returns all attribute values as they appeared before the update
- :updated-old returns only the updated attributes as they appeared before the update
- :all-new returns all attribute values as they appear after the update
- :updated-new returns only the updated attributes, as they appear after the update
First we'll add a few new attributes to our existing :music table:
Since we requested :all-new, we'll get the entire item back.
But we're not limited to one update per expression - we can (for example) both set a price and remove an element using path notation.
So long, Mr. Davis.
Specify a conditional write
Much like we added a conditional expression to put-item back on part 1, we can also send a condition expression to our update-item call.
Which will get us a ConditionalCheckFailedException since the attribute "label" - which we specified on :cond-expr shouldn't exist - is already there.
Specify an atomic counter
We'll now kill two birds with one stone: we'll demo how to do an atomic counter, and retrieve only the updated attributes for the item.
Let's first set a new plays attribute to zero.
We can now use a function on update-item's update expression to increase it.
If we execute that same call multiple times, the item is updated as expected.
Delete an item
We can also permanently delete an item using its full hash key.
And poof! It's gone, forever.
Specify a conditional delete
You won't be surprised to find that deletes also support conditional expressions. We can add a check that, if it goes unsatisfied, will let us know by raising an exception.
Which, as before, gets us a ConditionalCheckFailedException because the item does not have the expected price.
Deleting a table
And finally, we can delete a table on its entirety.
This will return the table's last status.
And we're done!
That's it! As you can see, Faraday provides a significantly more succinct interface to DynamoDB than even Amazon's unceremonious Javascript API. It's a growing project, but a great companion to Amazon's document store.
Discussion in the ATmosphere