batchWriteItem具有相同的分区键

时间:2016-08-05 20:06:36

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

我有一个带有分区键id和排序键value

的dynamodb表

现在我想运行batchWriteItem来插入具有相同分区键和不同排序键的多个项目,但它只插入最后一项:

$response = $dynamoDb->batchWriteItem([
    'RequestItems' => [
        'mytable' => [
            [
                'PutRequest' => [
                    'Item' => [
                        'id' => array('S' => '123abc'),
                        'value' => array('N' => '1'),
                    ],
                    'Item' => [
                        'id' => array('S' => '123abc'),
                        'value' => array('N' => '2'),
                    ],
                    'Item' => [
                        'id' => array('S' => '123abc'),
                        'value' => array('N' => '3'),
                    ]],

            ],
        ],

    ],
]);

使用此代码,只会插入值为3的项目

 "Items": [
        {
            "id": {
                "S": "123abc"
            },
            "value": {
                "N": "3"
            }
        }
    ],

代码有什么问题或者我没有考虑过吗?

在执行单个请求时,它非常有效:

$response = $dynamoDb->putItem(array(
    'TableName' => 'mytable',
    'Item' => array(
        'id' => array('S' => '123abc'),
        'value' => array('N' => '1'),
    ),
));

$response = $dynamoDb->putItem(array(
    'TableName' => 'mytable',
    'Item' => array(
        'id' => array('S' => '123abc'),
        'value' => array('N' => '2'),
    ),
));

$response = $dynamoDb->putItem(array(
    'TableName' => 'mytable',
    'Item' => array(
        'id' => array('S' => '123abc'),
        'value' => array('N' => '3'),
    ),
));

batchWriteItem或按顺序执行3次单putItem次请求之间是否存在任何性能差异?

1 个答案:

答案 0 :(得分:2)

您对batchWrite使用的语法不正确,请尝试按照

$response = $dynamoDb->batchWriteItem([
    'RequestItems' => [
        'mytable' => [
            [
                'PutRequest' => [   
                    'Item' => [
                        'id' => array('S' => '123abc'),
                        'value' => array('N' => '1'),
                    ]
                    ],
                    'PutRequest' => [  ///Entire PutRequest array need to be repeated not just item array///
                       'Item' => [
                        'id' => array('S' => '123abc'),
                        'value' => array('N' => '2'),
                    ]
                    ],
            ],
        ],

    ],
]);

除此之外,单个插入和多个插入之间的区别在于连接DynamoDB的调用,在batchPut中,您将立即发送整个数组,而在单个插入中,每次尝试执行任何操作时,它将连接到DB

通常,您可以使用Batch来更快地处理事情。

以下是引用link for batchWrite syntax

希望有所帮助。