Amazon SimpleDB

このガイドは、 Amazon SimpleDB のためのニフティクラウド SDK for PHP クライアントにフォーカスしています。 このガイドでは、 ニフティクラウド SDK for PHPをダウンロードしインストールが既に終わっていると想定しています。 はじめる場合のより詳細な情報は インストール を参照して下さい。

利用可能な操作

利用可能なすべてのメソッドおよび入出力の記述についてのより詳細な情報を得るためには ニフティクラウド API リファレンス または Amazon SimpleDB クライアント API リファレンス を参照して下さい。

BatchDeleteAttributes BatchPutAttributes
CreateDomain DeleteAttributes
DeleteDomain DomainMetadata
GetAttributes ListDomains
PutAttributes Select

クライアントの作成

まず以下のような方法のいずれかで、クライアントオブジェクトを作成しなければなりません。

Factory method

Aws\SimpleDb\SimpleDbClient::factory() メソッドを利用することで、最も簡単に立ち上げ速やかに動かすことができます。その際にクレデンシャル (key and secret) を提供して下さい。

region パラメータも必須で、以下の値のいずれかをセットしなければなりません。: us-east-1, ap-northeast-1, sa-east-1, ap-southeast-1, us-west-2, us-west-1, eu-west-1

use Aws\SimpleDb\SimpleDbClient;

$client = SimpleDbClient::factory(array(
    'key'    => '<aws access key>',
    'secret' => '<aws secret key>',
    'region' => '<region name>'
));

先の例のようにしてアクセスキーをセットすることができます。また、もし、 AWS Identity and Access Management (IAM) roles for EC2 instances を利用しているか、環境変数 AWS_ACCESS_KEY_IDAWS_SECRET_ACCESS_KEY からクレデンシャル情報を利用できるのであれば、これらの設定を省略することも可能です。

サービスロケータ

より確実に Amazon SimpleDB に接続する方法はサービスロケータを通す方法です。 設定ファイルの中でクレデンシャルと設定値を指定することができます。 これらの設定はすべてのクライアントで共有されるので一度だけ設定を行えばよくなります。

use Aws\Common\Aws;

// Create a service builder using a configuration file
$aws = Aws::factory('/path/to/my_config.json');

// Get the client from the builder by namespace
$client = $aws->get('SimpleDb');

Creating domains

The first step in storing data within Amazon SimpleDB is to create one or more domains.

Domains are similar to database tables, except that you cannot perform functions across multiple domains, such as querying multiple domains or using foreign keys. As a consequence, you should plan an Amazon SimpleDB data architecture that will meet the needs of your project.

Let's use the CreateDomain operation of the Amazon SimpleDB client to create a domain.

$client->createDomain(array('DomainName' => 'mydomain'));

List all domains

Now that the domain is created, we can list the domains in our account to verify that it exists. This is done using the ListDomains operation and the ListDomains iterator.

$domains = $client->getIterator('ListDomains')->toArray();
var_export($domains);
// Lists an array of domain names, including "mydomain"

Retrieving a domain

You can get more information about a domain using the DomainMetadata operation. This operation returns information about a domain, including when the domain was created, the number of items and attributes, and the size of attribute names and values.

$result = $client->domainMetadata(array('DomainName' => 'mydomain'));
echo $result['ItemCount'] . "\n";
echo $result['ItemNamesSizeBytes'] . "\n";
echo $result['AttributeNameCount'] . "\n";
echo $result['AttributeNamesSizeBytes'] . "\n";
echo $result['AttributeValueCount'] . "\n";
echo $result['AttributeValuesSizeBytes'] . "\n";
echo $result['Timestamp'] . "\n";

Adding items

After creating a domain, you are ready to start putting data into it. Domains consist of items, which are described by attribute name-value pairs. Items are added to a domain using the PutAttributes operation.

$client->putAttributes(array(
    'DomainName' => 'mydomain',
    'ItemName'   => 'test',
    'Attributes' => array(
        array('Name' => 'a', 'Value' => 1, 'Replace' => true),
        array('Name' => 'b', 'Value' => 2),
    )
));

Note

When you put attributes, notice that the Replace parameter is optional, and set to false by default. If you do not explicitly set Replace to true, a new attribute name-value pair is created each time; even if the Name value already exists in your Amazon SimpleDB domain.

Retrieving items

GetAttributes

We can check to see if the item was added correctly by retrieving the specific item by name using the GetAttribute operation.

$result = $client->getAttributes(array(
    'DomainName' => 'mydomain',
    'ItemName'   => 'test',
    'Attributes' => array(
        'a', 'b'
    ),
    'ConsistentRead' => true
));

Notice that we set the ConsistentRead option to true. Amazon SimpleDB keeps multiple copies of each domain. A successful write (using PutAttributes, BatchPutAttributes, DeleteAttributes, BatchDeleteAttributes, CreateDomain, or DeleteDomain) guarantees that all copies of the domain will durably persist. Amazon SimpleDB supports two read consistency options: eventually consistent read and consistent read. A consistent read (using Select or GetAttributes with ConsistentRead=true) returns a result that reflects all writes that received a successful response prior to the read.

You can find out more about consistency and Amazon SimpleDB in the service's developer guide on consistency.

Select

You can retrieve attributes for items by name, but Amazon SimpleDB also supports the Select operation. The Select operation returns a set of Attributes for ItemNames that match the select expression. Select is similar to the standard SQL SELECT statement.

Let's write a select query that will return all items withe the a attribute set to 1.

$result = $client->select(array(
    'SelectExpression' => "select * from mydomain where a = '1'"
));
foreach ($result['Items'] as $item) {
    echo $item['Name'] . "\n";
    var_export($item['Attributes']);
}

Because some responses will be truncated and require subsequent requests, it is recommended to always use the Select iterator to easily retrieve an entire result set.

$iterator = $client->getIterator('Select', array(
    'SelectExpression' => "select * from mydomain where a = '1'"
));
foreach ($iterator as $item) {
    echo $item['Name'] . "\n";
    var_export($item['Attributes']);
}

You can find much more information about the Select operation in the service's developer guide on select.

Deleting items

You can delete specific attributes of an item or an entire item using the DeleteAttributes operation. If all attributes of an item are deleted, the item is deleted.

Let's go ahead and delete the item we created in mydomain.

$client->deleteAttributes(array(
    'DomainName' => 'mydomain',
    'ItemName'   => 'test'
));

Because we did not specify an Attributes parameter, the entire item is deleted.

Deleting domains

Now that we've explored some of the features of Amazon SimpleDB, we should delete our testing data. The DeleteDomain operation deletes a domain. Any items (and their attributes) in the domain are deleted as well. The DeleteDomain operation might take 10 or more seconds to complete.

$client->deleteDomain(array('DomainName' => 'mydomain'));