Amazon DynamoDB
Developer Guide (API Version 2012-08-10)
« 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.Did this page help you?  Yes | No |  Tell us about it...

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

The query function enables you to query a table. You can only query a table that has a primary key composed of hash and range attributes.

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

  1. Create an instance of the DynamoDbClient class (the client).

  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.

use Aws\DynamoDb\DynamoDbClient;
use Aws\DynamoDb\Enum\Type;
use Aws\DynamoDb\Enum\ComparisonOperator;

// Instantiate the client with your AWS access keys
$aws = Aws\Common\Aws::factory("./config.php");
$client = $aws->get("dynamodb");

$response = $client->query(array(
    "TableName" => "Reply",
    "KeyConditions" => array(
        "Id" => array(
            "ComparisonOperator" => ComparisonOperator::EQ,
            "AttributeValueList" => array(
                array(Type::STRING => "DynamoDB#DynamoDB Thread 1")
            )
        )
    )
));

print_r($response[Items]);

Specifying Optional Parameters

The query function supports several optional parameters. For example, you can optionally filter 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.

  • AttributesToGet to specify a list of 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.

use Aws\DynamoDb\Enum\ComparisonOperator;

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

$response = $client->query(array(
    "TableName" => "Reply",
    "KeyConditions" => array(
        "Id" => array(
            "ComparisonOperator" => ComparisonOperator::EQ,
            "AttributeValueList" => array(
                array(Type::STRING => "DynamoDB#DynamoDB Thread 2")
            )
        ),
        // optional range key condition
        "ReplyDateTime" => array(
            "ComparisonOperator" => ComparisonOperator::GE,
            "AttributeValueList" => array(
                array(Type::STRING => $fourteenDaysAgo)
            )
        )
    ),
    // optional parameters
    "AttributesToGet" => array( "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;
use Aws\Common\Enum\Region;
use Aws\DynamoDb\Enum\Type;
use Aws\DynamoDb\Enum\ComparisonOperator;

// Instantiate the client with your AWS access keys
$aws = Aws\Common\Aws::factory("./config.php");
$client = $aws->get("dynamodb");

$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" . PHP_EOL;
    $request = array(
        "TableName" => $tableName,
        "KeyConditions" => array(
            "Id" => array(
                "ComparisonOperator" => ComparisonOperator::EQ,
                "AttributeValueList" => array(
                    array(Type::STRING => "DynamoDB#DynamoDB Thread 2")
                )
            ),
            "ReplyDateTime" => array(
                "ComparisonOperator" => ComparisonOperator::GE,
                "AttributeValueList" => array(
                    array(Type::STRING => $fourteenDaysAgo)
                )
            )
        ),
        "AttributesToGet" => array("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 = $client->query($request);

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

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

?>