Amazon DynamoDB
Developer Guide (API Version 2012-08-10)
Did this page help you?  Yes | No |  Tell us about it...
« PreviousNext »
View the PDF for this guide.Go to the AWS Discussion Forum for this product.Go to the Kindle Store to download this guide in Kindle format.

Querying Tables Using the AWS SDK for PHP Low-Level API

The query function enables you to query a table or a secondary index. You must provide a hash key value and an equality condition. If the table or index has a range key, you can refine the results by providing a range key value and a condition.

The following steps guide you through querying using the AWS SDK for PHP.

  1. Create an instance of the DynamoDbClient class.

  2. Provide the parameters for the query operation to the client instance.

    You must provide the table name, any desired item's primary key values, and any optional query parameters. You can set up a condition as part of the query if you want to find a range of values that meet specific comparison results. You can limit the results to a subset to provide pagination of the results. Read results are eventually consistent by default. If you want, you can request that read results be strongly consistent instead.

  3. Load the response into a local variable, such as $response, for use in your application.

Consider the following Reply table that stores replies for forum threads.

Reply ( Id, ReplyDateTime, ... )

Each forum thread has a unique ID and can have zero or more replies. Therefore, the primary key is made of both the Id (hash attribute) and ReplyDateTime (range attribute).

The following query retrieves all replies for a specific thread subject. The query requires the table name and the Subject value.

Note

This code example assumes that you have already loaded data into DynamoDB for your account by following the instructions in the Getting Started section. Alternatively, you can load the data programmatically using the instructions in the Creating Example Tables and Uploading Data Using the AWS SDK for PHP topic.

For step-by-step instructions to run the following example, see Running PHP Examples.

$client = DynamoDbClient::factory(array(
    'profile' => 'default',
    'region' => 'us-east-1' #replace with your desired region     
));

$response = $client->query(array(
    'TableName' => 'Reply',
    'KeyConditions' => array(
        'Id' => array(
            'ComparisonOperator' => 'EQ',
            'AttributeValueList' => array(
                array('S' => 'Amazon DynamoDB#DynamoDB Thread 1')
            )
        )
    )
));

print_r($response['Items']);

Specifying Optional Parameters

The query function supports several optional parameters. For example, you can optionally narrow the query result in the preceding query to return replies in the past two weeks by specifying a range condition. The condition is called a range condition because DynamoDB evaluates the query condition you specify against the range attribute of the primary key. You can specify other optional parameters to retrieve a specific list of attributes from items in the query result. For more information about the parameters, see Query.

The following PHP example retrieves forum thread replies posted in the past 7 days. The sample specifies the following optional parameters:

  • The range key attribute in the KeyCondition parameter to retrieve only the replies within the last 7 days.

    The condition specifies ReplyDateTime value and a comparison operator to use for comparing dates.

  • ProjectionExpression to specify the attributes to retrieve for items in the query results

  • ConsistentRead parameter to perform a strongly consistent read. This overrides the default behavior of perform an eventually consistent reads. To learn more about read consistency, see Data Read and Consistency Considerations.

$client = DynamoDbClient::factory(array(
    'profile' => 'default',
    'region' => 'us-east-1' #replace with your desired region
));

date_default_timezone_set("UTC");
$sevenDaysAgo = date('Y-m-d H:i:s', strtotime('-7 days'));

$response = $client->query(array(
    'TableName' => 'Reply',
    'KeyConditions' => array(
        'Id' => array(
            'ComparisonOperator' => 'EQ',
            'AttributeValueList' => array(
                array('S' => 'Amazon DynamoDB#DynamoDB Thread 2')
            )
        ),
        // optional range key condition
        'ReplyDateTime' => array(
            'ComparisonOperator' => 'GE',
            'AttributeValueList' => array(
                array('S' => $sevenDaysAgo)
            )
        )
    ),
    // optional parameters
    'ProjectionExpression' => 'Subject, ReplyDateTime, PostedBy',
    'ConsistentRead' => true
));

print_r($response['Items']);

You can also optionally limit the page size, the number of items per page, by adding the Limit parameter. Each time you execute the query function, you get one page of results with the specified number of items. To fetch the next page you execute the query function again by providing primary key value of the last item in the previous page so the method can return the next set of items. You provide this information in the request by setting the ExclusiveStartKey property. Initially this property can be null. For retrieving subsequent pages you must update this property value to the primary key of the last item in the preceding page.

The following PHP example queries the Reply table for entries that are more than 14 days old. In the request it specifies the Limit and ExclusiveStartKey optional parameters.

<?php

use Aws\DynamoDb\DynamoDbClient;

$client = DynamoDbClient::factory(array(
    'profile' => 'default',
    'region' => 'us-east-1'  // replace with your desired region
));

$tableName = 'ExampleTable';

echo "# Creating table $tableName..." . PHP_EOL;

$response = $client->createTable(array(
    'TableName' => $tableName,
    'AttributeDefinitions' => array(
        array(
            'AttributeName' => 'Id',
            'AttributeType' => 'N'
        )
    ),
    'KeySchema' => array(
        array(
            'AttributeName' => 'Id',
            'KeyType' => 'HASH'
        )
    ),
    'ProvisionedThroughput' => array(
        'ReadCapacityUnits'    => 5,
        'WriteCapacityUnits' => 6
    )
));

print_r($response->getPath('TableDescription'));

$client->waitUntilTableExists(array('TableName' => $tableName));
echo "table $tableName has been created." . PHP_EOL;

####################################################################
# Updating the table

echo "# Updating the provisioned throughput of table $tableName." . PHP_EOL; 

$response = $client->updateTable(array(
    'TableName' => $tableName,
    'ProvisionedThroughput'    => array(
        'ReadCapacityUnits'    => 6,
        'WriteCapacityUnits' => 7
    )
));

// Wait until update completes
$client->waitUntilTableExists(array('TableName' => $tableName));

echo "New provisioned throughput settings:" . PHP_EOL;


echo "Read capacity units: " . $response['TableDescription']['ProvisionedThroughput']['ReadCapacityUnits'] . PHP_EOL;
echo "Write capacity units: " . $response['TableDescription']['ProvisionedThroughput']['WriteCapacityUnits'] . PHP_EOL;

####################################################################
# Deleting the table

echo "# Deleting table $tableName..." . PHP_EOL;

$response = $client->deleteTable(array(
    'TableName' => $tableName
));

$client->waitUntilTableNotExists(array('TableName' => $tableName));
echo "The table has been deleted." . PHP_EOL;

####################################################################
# Collect all table names in the account

echo "# Listing all the tables in the account..." . PHP_EOL;

$tables = array();

// Walk through table names, two at a time

do {
    $response = $client->listTables(array(
        'Limit' => 2,    
        'ExclusiveStartTableName' => isset($response) ? $response['LastEvaluatedTableName'] : null
    )); 

    foreach ($response['TableNames'] as $key => $value) {
        echo "$value" . PHP_EOL;
    }

    $tables = array_merge($tables, $response['TableNames']);

}
while ($response['LastEvaluatedTableName']);

// Print total number of tables

echo "Total number of tables: ";
print_r(count($tables));
echo PHP_EOL;

?>