How can I get the total number of items in a DynamoDB table?

前端 未结 8 2023
南旧
南旧 2020-12-05 23:33

I want to know how many items are in my dynamodb table. From the API guide, one way to do it is using a scan as follows:



        
相关标签:
8条回答
  • 2020-12-06 00:13

    Aha, there is a Count option in the scan API, see http://docs.amazonwebservices.com/AWSSDKforPHP/latest/#m=AmazonDynamoDB/scan

    <?php
    $dynamodb = new DynamoMetadata();
    
    $scan_response = $dynamodb->scan(array(
        'TableName' => 'ProductCatalog'
        'Count'     => true,
    ));
    
    echo "Count: ".$scan_response->body->Count."\n";
    
    0 讨论(0)
  • 2020-12-06 00:21

    The Count option is definitely what you want, but you also have to take into account that there may be one or more "page" of results in your Scan result. The Scan operation only scans 1MB of data in your table at a time, so the value of Count in the result is only going to reflect the count of the first 1MB of the table. You will need to make subsequent requests using the value of LastEvaluatedKey in the result (if it is there). Here is some sample code for doing something like that:

    <?php
    
    $dynamo_db = new AmazonDynamoDB();
    
    $total = 0;
    $start_key = null;
    $params = array(
        'TableName' => 'my-table',
        'Count'     => true
    );
    
    do {
        if ($start_key) {
            $params['ExclusiveStartKey'] = $start_key->getArrayCopy();
        }
    
        $response = $dynamo_db->scan($params);
    
        if ($response->isOK()) {
            $total += (string) $response->body->Count;
    
            if ($response->body->LastEvaluatedKey) {
                $start_key = $response->body->LastEvaluatedKey->to_array();
            } else {
                $start_key = null;
            }
        }
    } while ($start_key);
    
    echo "Count: {$total}";
    
    0 讨论(0)
提交回复
热议问题