使用PHP AWS SDK在DynamoDB中存储JSON文档

时间:2015-09-04 10:22:36

标签: php json amazon-web-services amazon-dynamodb aws-sdk

我阅读了documentation,其中有PHP示例,可以使用AWS SDK在dynamicDB表中插入数据。但这是表格数据。我试图插入JSON数据,即键值对,其中值是JSON文档。我该怎么做?

我尝试了doc中的以下代码,但除非value是数组,否则它不起作用。

<?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
    )
));

它给了我以下错误

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

1 个答案:

答案 0 :(得分:4)

DynamoDB要求您使用请求指定AttributeValue类型。以下是https://docs.aws.amazon.com/aws-sdk-php/v2/guide/service-dynamodb.html的示例:

In [39]: a[1, 0] = 99

In [40]: a
Out[40]: 
array([[ 0,  1],
       [99,  3],
       [ 4,  5]])

In [41]: b
Out[41]: 
array([[ 0,  3],
       [ 1,  4],
       [99,  5]])

对于您的示例,请尝试添加DynamoDB类型:

$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')
    )
));

'S'可以替换为'N','B','SS','NS','BS','M','L'或'BOOL',如下所示:{{3 }}