Menu
Amazon DynamoDB
Developer Guide (API Version 2012-08-10)

Querying Tables and Indexes: PHP

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

The following are the common steps for using the AWS SDK for PHP.

  1. Create an instance of the DynamoDB client.

  2. Provide the parameters for a DynamoDB operation, including any optional parameters.

  3. Load the response from DynamoDB into a local variable for 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 (partition key) and ReplyDateTime (sort key).

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

Note

This code sample assumes that you have already loaded data into DynamoDB for your account by following the instructions in the Creating Tables and Loading Sample Data section. Alternatively, you can load the data 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 PHP Code Samples.


require 'vendor/autoload.php';

$sdk = new Aws\Sdk([
    'region'   => 'us-west-2',
    'version'  => 'latest'
]);

$dynamodb = $sdk->createDynamoDb();

$response = $dynamodb->query([
    'TableName' => 'Reply',
    'KeyConditionExpression' => 'Id = :v_id',
    'ExpressionAttributeValues' =>  [
        ':v_id' => ['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 sort key condition. The condition is called a sort key condition, because DynamoDB evaluates the query condition you specify against the sort 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 sort key in the KeyConditionExpression 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 Read Consistency.


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

$response = $dynamodb->query([
    'TableName' => 'Reply',
    'KeyConditionExpression' => 'Id = :v_id and ReplyDateTime >= :v_reply_dt',
    'ExpressionAttributeValues' =>  [
        ':v_id' => ['S' => 'Amazon DynamoDB#DynamoDB Thread 2'],
        ':v_reply_dt' => ['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
require 'vendor/autoload.php';

date_default_timezone_set('UTC');

use Aws\DynamoDb\Exception\DynamoDbException;

$sdk = new Aws\Sdk([
    'region'   => 'us-west-2',
    'version'  => 'latest'
]);

$dynamodb = $sdk->createDynamoDb();

$fourteenDaysAgo = date('Y-m-d H:i:s', strtotime('-14 days'));
$tableName = 'Reply';

# The Query API is paginated. Issue the Query request multiple times.
do {
    echo "Querying table $tableName\n";

    $request = [
        'TableName' => $tableName,
        'KeyConditionExpression' => 'Id = :v_id and ReplyDateTime >= :v_reply_dt',
        'ExpressionAttributeValues' =>  [
            ':v_id' => ['S' => 'Amazon DynamoDB#DynamoDB Thread 2'],
            ':v_reply_dt' => ['S' => $fourteenDaysAgo]
        ],
        'ProjectionExpression' => 'Id, ReplyDateTime, Message, PostedBy',
        'ConsistentRead' => true,
        'Limit' => 1
    ];

    # Add the ExclusiveStartKey if we got one back in the previous response
    if(isset($response) && isset($response['LastEvaluatedKey'])) {
        $request['ExclusiveStartKey'] = $response['LastEvaluatedKey'];
    }

    $response = $dynamodb->query($request);

    foreach ($response['Items'] as $key => $value) {
        echo 'Id: ' . $value['Id']['S'] . "\n";
        echo 'ReplyDateTime: ' . $value['ReplyDateTime']['S'] . "\n";
        echo 'Message: ' . $value['Message']['S'] . "\n";
        echo 'PostedBy: ' . $value['PostedBy']['S'] . "\n"; 
        echo "\n";
    }

# If there is no LastEvaluatedKey in the response, then 
# there are no more items matching this Query
} while(isset($response['LastEvaluatedKey'])); 

?>