Neil
Neil

Reputation: 6039

Storing JSON document in DynamoDB using PHP AWS SDK

I read the documentation where there are PHP examples to insert data in a dynamicDB table using AWS SDK. However this is for tabular data. I am trying to insert JSON data i.e. Key Value pair where value is a JSON document. How do I do that ?

I tried the following code from the doc but it does not work unless value is an array.

<?php

require '/home/ubuntu/vendor/autoload.php';

use Aws\DynamoDb\DynamoDbClient;

$client = DynamoDbClient::factory(array(
    'profile' => 'default',
    'region'  => 'ap-southeast-1',
    'version' => '2012-08-10'
));

$id = "key";
$value = '{"subKey":"value"}'


$result = $client->putItem(array(
    'TableName' => 'myTable',
    'Item' => array(
        'key'  => $value
    )
));

It gave me following error

Fatal error: Uncaught exception 'InvalidArgumentException' with message 'Found 2 errors while validating the input provided for the PutItem operation: [Item][key] must be an associative array. Found string(1) "2" [Item][userId] must be an associative array. Found string(18) "{"subKey":"value"}"' in /home/ubuntu/vendor/aws/aws-sdk-php/src/Api/Validator.php:38 Stack trace: #0 /home/ubuntu/vendor/aws/aws-sdk-php/src/Middleware.php(78): Aws\Api\Validator->validate('PutItem', Object(Aws\Api\StructureShape), Array) #1 /home/ubuntu/vendor/aws/aws-sdk-php/src/AwsClient.php(208): Aws\Middleware::Aws\{closure}(Object(Aws\Command)) #2 /home/ubuntu/vendor/aws/aws-sdk-php/src/AwsClient.php(202): Aws\AwsClient->executeAsync(Object(Aws\Command)) #3 /home/ubuntu/vendor/aws/aws-sdk-php/src/AwsClient.php(167): Aws\AwsClient->execute(Object(Aws\Command)) #4 /var/www/html/dynamoDB.php(25): Aws\AwsClient->__call('putItem', Array) #5 /var/www/html/dynamoDB.php(25): Aws\DynamoDb\DynamoDbClient->putItem(Array) #6 {main} thrown in /home/ubuntu/vendor/aws/aws-sdk-php/src/Api/Validator.php on line 38

Upvotes: 2

Views: 3860

Answers (1)

Ben Schwartz
Ben Schwartz

Reputation: 1756

DynamoDB requires you specify the AttributeValue types with the request. Here is the example from https://docs.aws.amazon.com/aws-sdk-php/v2/guide/service-dynamodb.html:

$result = $client->putItem(array(
    'TableName' => 'errors',
    'Item' => array(
        'id'      => array('N' => '1201'),
        'time'    => array('N' => $time),
        'error'   => array('S' => 'Executive overflow'),
        'message' => array('S' => 'no vacant areas')
    )
));

For your example try adding DynamoDB types:

$result = $client->putItem(array(
    'TableName' => 'myTable',
    'Item' => array(
        'key'  => array('S' => $value)
    )
));

Where 'S' could be replaced with 'N', 'B', 'SS', 'NS', 'BS', 'M', 'L', or 'BOOL' as defined here: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DataModel.html#DataModel.DataTypes

Upvotes: 4

Related Questions