![](/img/trans.png)
[英]Empty ResultSet for non-empty database table after PreparedStatement
[英]DynamoDB - how to check that an existing table is empty or non-empty
我正在尝试实现给定DynamoDB和数据库中已知的表名的函数,该函数确定该表是否为空。
我希望签名在Java中看起来像以下内容:
public Boolean isEmpty(DynamoDB database, String tableName) = ???
出于这个问题的目的,假定表具有一个主键,该主键由一个称为“ UserId”的整数类型属性组成。
我知道人们可以使用扫描来查看表,但是我(a)不知道表达式的外观,并且(b)需要将其限制为单个项目,因此我们不必如果它不是空的,则不必扫描整个表(可能很大)。
编辑:
我是否应该在构造函数中使用AmazonDynamoDB
而不是DynamoDB
? 前者有一个采用ScanRequest
的scan
方法-您可以使用.limit(1)
轻松地设置限制-而对于后者,我会做诸如database.getTable(tableName).scan(...)
,但是这次扫描需要一个ScanSpec
,我不清楚如何为此设置限制。
我不知道如何用Java来做,但是它必须类似于Javascript:
const params = {
TableName: tableName,
Limit: 1, // `Limit` is the most important parameter.
// The scan will not scan the whole table,
// it will only visit one item and then return.
// Very efficient!
};
// Execute the scan, whatever the syntax is...
const result = await (new AWS.DynamoDB.DocumentClient().scan(params).promise());
// Check the response
if (result.Count > 0) return false; // the table is **not** empty
return true; // the table is empty
在Java中,代码应类似...请随时询问细节,但不够清楚。
在回答我自己的问题时,我发现以下内容: 它们的Java SDK中的AmazonDynamoDBClient和DynamoDB类之间的区别?
我尝试使用的DynamoDB
只是AmazonDynamoDB
的包装,提供了稍微不同的API。 相反,使用AmazonDynamoDB
可以使此功能的实现更加容易,并且它应该看起来像这样(请原谅不好的Java代码,我实际上是在Scala中编写的):
public Boolean isEmpty(AmazonDynamoDB database, String tableName) = {
ScanRequest scanRequest = new ScanRequest().withTableName(tableName).withLimit(1);
return database.scan(scanRequest).getCount == 0;
}
或者,在Scala中:
def isEmpty(database: AmazonDynamoDB, tableName: String): Boolean = {
val scanRequest = new ScanRequest().withTableName(tableName).withLimit(1)
database.scan(scanRequest).getCount == 0
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.