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

我有一个名为 products 的表,其主键为 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),
),
)
)
)
));

是否可以不指定主键选择所有项目? 我正在使用 AWS SDK for PHP。

183506 次浏览

Amazon DynamoDB 为此提供了 扫描操作,即 通过对表进行全面扫描,返回一个或多个项及其属性:

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

    注意
    如果扫描项的总数超过1MB 限制,则 扫描停止和结果返回给用户 在随后的操作中继续扫描 结果还包括超出限制的项目数量 可能导致没有符合筛选条件的表数据。

    结果集最终是一致的。

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

    [ ... ]而且,随着表的增长,扫描操作会变慢 Operation 检查每个项以获得所请求的值,< strong > 可能会用完 在单个操作 中为大型表提供的吞吐量。 为了缩短响应时间,请以一种可以使用 查询、获取或 BatchGetItem API,或者设计您的 应用程序使用扫描操作的方式,以最大限度地减少影响 欲了解更多信息,请参见 http://docs.amazonwebservices.com/amazondnamodb/best/developerguide/BestPractices.html”rel = “ noReferrer”> Provisioned Amazon DynamoDB 中的吞吐量指南

您可以在 使用 AWS SDK for PHP 低级 API for Amazon DynamoDB 扫描表中找到关于这个操作的更多细节和一些示例片段,其中最简单的示例说明了这个操作:

$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>";
}

我使用以下查询从 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']);

我认为你正在使用 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));
}
});

我认为 同样的代码可以翻译成 PHP也是 使用不同的 AWS SDK

这段 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 & data 中创建您想要获取的数据

你好,你可以下载使用 boto3.inpython

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'])


通过指定 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}")

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

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

下面是 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