I am trying to interact with AWS DynamoDB from my website with AWS SDK PHP 3.0 using the code below:
$client = new \Aws\DynamoDb\DynamoDbClient(['version' => 'latest', 'region' => "ca-central-1"]);
$result_put = $client->putItem(array(
"TableName" => "Table_name",
"Item" => array(
"PK" => array("S" => "TEST"),
"SK" => array('S' => "123456")
)
));
$result_get = $client->getItem(array(
"TableName" => "Table_name",
"Key" => array(
"PK" => array("S" => "TEST"),
"SK" => array("S" => "123456")
)
));
I can put items in the table, however getItem always returns {}
, even when I ask for 'ReturnConsumedCapacity' => 'INDEXES'
.
My IAM permissions are:
{
"Effect": "Allow",
"Action": "dynamodb:*",
"Resource": "arn:aws:dynamodb:*:xxx:table/Table_name"
}
It works perfectly with AWS CLI. But I don't know what else to try to find the cause of the error in PHP.
Judging by how you show the code, you are doing a read after write.
DynamoDB clients are eventually consistent by default, that is that you write to the leader node, and straight away perform a read. That read is served by a follower node, which has not yet received the item from the leader, giving you the impression the item didn't save.
To perform read after write, you'll want to force your request to be strongly consistent, so the read is directed to the leader, who accepted the write and is always up to date with the latest data.
Furthermore, you must check that
$result_put
receives a 200 status code, I don't write PHP so was unable to add that to the below code.https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.ReadConsistency.html