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

Storing JSON document in DynamoDB using PHP AWS SDK

我阅读了 documentation,其中有 PHP 使用 AWS SDK 将数据插入动态数据库 table 的示例。但是,这是针对表格数据的。我正在尝试插入 JSON 数据,即键值对,其中值是 JSON 文档。我该怎么做?

我尝试了文档中的以下代码,但它不起作用,除非值是一个数组。

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

DynamoDB 要求您在请求中指定 AttributeValue 类型。这是来自 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')
    )
));

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

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

其中 'S' 可以替换为 'N'、'B'、'SS'、'NS'、'BS'、'M' 、'L' 或 'BOOL' 定义如下:https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DataModel.html#DataModel.DataTypes