如何在不指定主键的情况下从 DynamoDB 表中获取所有项目


How can I fetch all items from a DynamoDB table without specifying the primary key?

我有一个名为产品与主键Id的表。我想选择表中的所有项目。这是我正在使用的代码:

$batch_get_response = $dynamodb->batch_get_item(array(
    'RequestItems' => array(
        'products' => array(
            'Keys' => array(
                array( // Key #1
                    'HashKeyElement'  => array( AmazonDynamoDB::TYPE_NUMBER => '1'),
                    'RangeKeyElement' => array( AmazonDynamoDB::TYPE_NUMBER => $current_time),
                ),
                array( // Key #2
                    'HashKeyElement'  => array( AmazonDynamoDB::TYPE_NUMBER => '2'),
                    'RangeKeyElement' => array( AmazonDynamoDB::TYPE_NUMBER => $current_time),
                ),
            )
        )
    )   
));

是否可以在不指定主键的情况下选择所有项目?我正在使用适用于 PHP 的 AWS 开发工具包。

Amazon DynamoDB 为此提供了扫描操作,该操作通过对表执行完全扫描来返回一个或多个项目及其属性。请注意以下两个限制:

  • 根据您的表大小,您可能需要使用分页来检索整个结果集:

    注意
    如果扫描的项目总数超过 1MB 限制,则 扫描停止,结果返回给用户,并带有 上一个已评估的密钥以在后续操作中继续扫描。这 结果还包括超出限制的项目数。扫描 可能导致没有表数据满足筛选条件。

    结果集是最终一致的。

  • 扫描操作在性能和消耗的容量单位(即价格(方面都可能代价高昂,请参阅在 Amazon DynamoDB 中查询和扫描中的扫描和查询性能部分:

    [...]此外,随着表的增长,扫描操作会变慢。扫描 操作检查每个项目的请求值,并且可以用完 单个操作中大型表的预置吞吐量。 为了加快响应时间,请以可以使用的方式设计表。 而是查询、Get 或 BatchGetItem API。或者,设计您的 以最小化影响的方式使用扫描操作的应用程序 根据您餐桌的请求率。有关更多信息,请参阅预置 Amazon DynamoDB 中的吞吐量指南。[强调我的]

您可以在使用 适用于 Amazon DynamoDB 的 AWS 开发工具包 PHP 低级 API 扫描表中找到有关此操作的更多详细信息和一些示例代码段,最简单的示例说明了该操作:

$dynamodb = new AmazonDynamoDB();
$scan_response = $dynamodb->scan(array(
    'TableName' => 'ProductCatalog' 
));
foreach ($scan_response->body->Items as $item)
{
    echo "<p><strong>Item Number:</strong>"
         . (string) $item->Id->{AmazonDynamoDB::TYPE_NUMBER};
    echo "<br><strong>Item Name: </strong>"
         . (string) $item->Title->{AmazonDynamoDB::TYPE_STRING} ."</p>";
}
嗨,

您可以使用 boto3 下载。在蟒蛇中

import boto3
from boto3.dynamodb.conditions import Key, Attr
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('Table')
response = table.scan()
items = response['Items']
while 'LastEvaluatedKey' in response:
    print(response['LastEvaluatedKey'])
    response = table.scan(ExclusiveStartKey=response['LastEvaluatedKey'])
    items.extend(response['Items'])

我想你正在使用PHP,但没有提到(编辑(。我通过搜索互联网找到了这个问题,因为我得到了解决方案,对于那些使用 nodejs 的人来说,这是一个使用扫描的简单解决方案:

  var dynamoClient = new AWS.DynamoDB.DocumentClient();
  var params = {
    TableName: config.dynamoClient.tableName, // give it your table name 
    Select: "ALL_ATTRIBUTES"
  };
  dynamoClient.scan(params, function(err, data) {
    if (err) {
       console.error("Unable to read item. Error JSON:", JSON.stringify(err, null, 2));
    } else {
       console.log("GetItem succeeded:", JSON.stringify(data, null, 2));
    }
  });

我假设相同的代码也可以使用不同的 AWS 开发工具包转换为 PHP

我使用以下查询从dynamodb获取所有项目。它工作正常。我在Zend框架中创建这些函数泛型,并通过项目访问这些函数。

        public function getQuerydata($tablename, $filterKey, $filterValue){
            return $this->getQuerydataWithOp($tablename, $filterKey, $filterValue, 'EQ');
        }
        public function getQuerydataWithOp($tablename, $filterKey, $filterValue, $compOperator){
        $result = $this->getClientdb()->query(array(
                'TableName'     => $tablename,
                'IndexName'     => $filterKey,
                'Select'        => 'ALL_ATTRIBUTES',
                'KeyConditions' => array(
                    $filterKey => array(
                        'AttributeValueList' => array(
                            array('S' => $filterValue)
                        ),
                'ComparisonOperator' => $compOperator
            )
            )
        ));
            return $result['Items'];
        }
       //Below i Access these functions and get data.
       $accountsimg = $this->getQuerydataWithPrimary('accounts', 'accountID',$msgdata[0]['accountID']['S']);

一个简单的代码,用于通过指定 AWS 服务的区域来列出 DynamoDB 表中的所有项目。

import boto3
dynamodb = boto3.resource('dynamodb', region_name='ap-south-1')
table = dynamodb.Table('puppy_store')
response = table.scan()
items = response['Items']
# Prints All the Items at once
print(items)
# Prints Items line by line
for i, j in enumerate(items):
    print(f"Num: {i} --> {j}")

下面是一个 Java 的例子。在withAttributesToGet中,您可以指定要读取的确切内容。在运行之前,您必须将凭据文件放入 .aws 文件夹。

 public static final String TABLE_NAME = "table_name";
    public static final AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard()
            .withRegion(Regions.CA_CENTRAL_1)
            .build();
    public static void main(String[] args) throws IOException, InterruptedException {
        downloadAllRecords();
    }
    public static void downloadAllRecords() throws InterruptedException, IOException {
        final Object[] FILE_HEADER = {"key", "some_param"};
        CSVFormat csvFormat = CSVFormat.DEFAULT.withRecordSeparator("'n");
        CSVPrinter csvPrinter = new CSVPrinter(new FileWriter(TABLE_NAME + ".csv"), csvFormat);
        csvPrinter.printRecord(FILE_HEADER);
        ScanRequest scanRequest = new ScanRequest()
                .withTableName(TABLE_NAME)
                .withConsistentRead(false)
                .withLimit(100)
                .withAttributesToGet("key", "some_param");
        int counter = 0;
        do {
            ScanResult result = client.scan(scanRequest);
            Map<String, AttributeValue> lastEvaluatedKey = result.getLastEvaluatedKey();
            for (Map<String, AttributeValue> item : result.getItems()) {
                AttributeValue keyIdAttribute = item.getOrDefault("key", new AttributeValue());
                AttributeValue createdDateAttribute = item.getOrDefault("some_param", new AttributeValue());
                    counter++;
                    List record = new ArrayList();
                    record.add(keyIdAttribute.getS());
                    record.add(createdDateAttribute.getS());
                    csvPrinter.printRecord(record);
                    TimeUnit.MILLISECONDS.sleep(50);
            }
            scanRequest.setExclusiveStartKey(lastEvaluatedKey);
        } while (scanRequest.getExclusiveStartKey() != null);
        csvPrinter.flush();
        csvPrinter.close();
        System.out.println("CSV file generated successfully.");
    }

还要指定必要的依赖项。

<dependencies>
   <dependency>
       <groupId>com.sparkjava</groupId>
       <artifactId>spark-core</artifactId>
       <version>2.5.4</version>
   </dependency>
   <!-- https://mvnrepository.com/artifact/com.sparkjava/spark-template-velocity -->
   <dependency>
       <groupId>com.sparkjava</groupId>
       <artifactId>spark-template-velocity</artifactId>
       <version>2.7.1</version>
   </dependency>
   <!-- https://mvnrepository.com/artifact/com.amazonaws/aws-java-sdk-logs -->
   <dependency>
       <groupId>com.amazonaws</groupId>
       <artifactId>aws-java-sdk-logs</artifactId>
       <version>1.12.132</version>
   </dependency>
   <dependency>
       <groupId>com.google.code.gson</groupId>
       <artifactId>gson</artifactId>
       <version>2.8.9</version>
   </dependency>
   <dependency>
       <groupId>com.google.guava</groupId>
       <artifactId>guava</artifactId>
       <version>31.0.1-jre</version>
   </dependency>
   <dependency>
       <groupId>org.apache.commons</groupId>
       <artifactId>commons-collections4</artifactId>
       <version>4.4</version>
   </dependency>
   <dependency>
       <groupId>com.opencsv</groupId>
       <artifactId>opencsv</artifactId>
       <version>5.3</version>
   </dependency>
   <!-- https://mvnrepository.com/artifact/com.amazonaws/aws-java-sdk-dynamodb -->
   <dependency>
       <groupId>com.amazonaws</groupId>
       <artifactId>aws-java-sdk-dynamodb</artifactId>
       <version>1.12.161</version>
   </dependency>
   <dependency>
       <groupId>org.apache.commons</groupId>
       <artifactId>commons-csv</artifactId>
       <version>1.1</version>
   </dependency>
</dependencies>

凭据文件示例

[default]
aws_access_key_id = AAAAAAA
aws_secret_access_key = AAAAAAAA
aws_session_token = AAAAAAA

我没有在以下代码上指定 pk:

client = boto3.client('dynamodb')
table = 'table_name'
response = client.scan(
    TableName=table,
    AttributesToGet=['second_field_in_order', 'first_field_in_order']
)

在不使用主键和不运行 Scan 的情况下获取所有行的方法是在表上定义/添加 GSI(全局二级索引(,并具有一个可以指定为 GSI 键的附加属性。将此值设置为每行中的相同值(除非您要将其用于多种用途(

然后,对 GSI 执行查询,指定添加的属性的值。

您可能需要对返回的值进行分页。

使用 GSI 会增加表的大小,并可能增加成本。

此 C# 代码使用 BatchGet 或 CreateBatchGet 从 dynamodb 表中获取所有项目

        string tablename = "AnyTableName"; //table whose data you want to fetch
        var BatchRead = ABCContext.Context.CreateBatchGet<ABCTable>(  
            new DynamoDBOperationConfig
            {
                OverrideTableName = tablename; 
            });
        foreach(string Id in IdList) // in case you are taking string from input
        {
            Guid objGuid = Guid.Parse(Id); //parsing string to guid
            BatchRead.AddKey(objGuid);
        }
        await BatchRead.ExecuteAsync();
        var result = BatchRead.Results;

ABCTable 是用于在 dynamodb 中创建的表模式 &你想要获取的数据