本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
步骤 2:加载样本数据
在此步骤中,您将使用样本数据填充 Movies
表。
此方案将使用一个样本数据文件,其中包含与 Internet Movie Database (IMDb) 中的数千部电影相关的信息。如以下示例所示,电影数据是 JSON
格式。每部电影各有一个 year
、title
和一个名为 info
的 JSON 映射。
[ { "year" : ... , "title" : ... , "info" : { ... } }, { "year" : ..., "title" : ..., "info" : { ... } }, ... ]
在 JSON 数据中,请注意以下事项:
-
year
和title
用作Movies
表的主键属性值。 -
其余的
info
值存储在名为info
的单个属性中。 此程序演示了如何在 Amazon DynamoDB 属性中存储 JSON。
以下是一个电影数据的示例。
{ "year" : 2013, "title" : "Turn It Down, Or Else!", "info" : { "directors" : [ "Alice Smith", "Bob Jones" ], "release_date" : "2013-01-18T00:00:00Z", "rating" : 6.2, "genres" : [ "Comedy", "Drama" ], "image_url" : "http://ia.media-imdb.com/images/N/O9ERWAU7FS797AJ7LU8HN09AMUP908RLlo5JF90EWR7LJKQ7@@._V1_SX400_.jpg", "plot" : "A rock band plays their music at high volumes, annoying the neighbors.", "rank" : 11, "running_time_secs" : 5215, "actors" : [ "David Matthewman", "Ann Thomas", "Jonathan G. Neff" ] } }
步骤 2.1:下载样本数据文件
-
下载样本数据存档:moviedata.zip
-
从存档中提取数据文件 (
moviedata.json
)。 -
将
moviedata.json
文件复制并粘贴到当前目录中。
步骤 2.2:将示例数据加载到 Movies 表中
下载样本数据后,您可以运行以下程序来填充 Movies
表。
-
将以下程序复制并粘贴到名为
MoviesLoadData.php
的文件中。/** * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * This file is licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. A copy of * the License is located at * * http://aws.amazon.com/apache2.0/ * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ require 'vendor/autoload.php'; date_default_timezone_set('UTC'); use Aws\DynamoDb\Exception\DynamoDbException; use Aws\DynamoDb\Marshaler; $sdk = new Aws\Sdk([ 'endpoint' => 'http://localhost:8000', 'region' => 'us-west-2', 'version' => 'latest' ]); $dynamodb = $sdk->createDynamoDb(); $marshaler = new Marshaler(); $tableName = 'Movies'; $movies = json_decode(file_get_contents('moviedata.json'), true); foreach ($movies as $movie) { $year = $movie['year']; $title = $movie['title']; $info = $movie['info']; $json = json_encode([ 'year' => $year, 'title' => $title, 'info' => $info ]); $params = [ 'TableName' => $tableName, 'Item' => $marshaler->marshalJson($json) ]; try { $result = $dynamodb->putItem($params); echo "Added movie: " . $movie['year'] . " " . $movie['title'] . "\n"; } catch (DynamoDbException $e) { echo "Unable to add movie:\n"; echo $e->getMessage() . "\n"; break; } }
注意 封送拆收器类DynamoDB具有将 JSON 文档和 PHP 数组转换为 格式的方法。DynamoDB在此程序中,
$marshaler->marshalJson($json)
使用 JSON 文档并将其转换为 DynamoDB 项目。 -
要运行该程序,请输入以下命令。
php MoviesLoadData.php