Reputation: 35497
I am writing a "Get or Create" method that attempts to get an item, but if it doesn't exist, it will create a fresh new version of it. Obviously, I want to know for certain that the item didn't exist when I attempted to get it, so that it never overwrites existing data.
Am I correct in assuming $result["Item"] === null
if and only if the item did not exist in the database at the time of the request? That is, if the item existed prior to the request, will this condition always evaluate to false, regardless of API errors, etc.? Or is there something else I should check for instead?
$result = $this->client->getItem(
array(
"TableName" => $tableName,
"Key" => array(
$keyName => array(Type::STRING => $key),
)
)
);
if ( $result["Item"] === null )
{
//Item does not exist; create it and write it to dynamoDb (code not shown)
}
return $result["Item"];
Upvotes: 4
Views: 2695
Reputation: 7304
Consider a conditional put where you specify that the key must not exist before doing the put. This avoids any race condition, and takes only a single call. The only downside is that you must send the entire new item over the wire, even if it already exists.
Scroll down to the "specifying optional parameters" section here: http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LowLevelJavaItemCRUD.html#PutLowLevelAPIJava
The code should look something like this:
// Optional parameters Expected and ReturnValue.
Map<String, ExpectedAttributeValue> expected = new HashMap<>();
expected.put(
"hashKeyAttributeName",
new ExpectedAttributeValue()
.withValue(new AttributeValue().withS("hashKeyValue"))
.withExists(false)
);
Upvotes: 0
Reputation: 6517
I would add 'ConsistentRead' => true
in order to make sure your read is getting the absolute, most up-to-date data.
You are still going to have a potential race condition here where if multiple processes try to get the item and see that it is not there, then they will all try to write the item, but only one process won't have its data clobbered. As long as there is no chance that they will write different data, then it doesn't matter.
Upvotes: 3