DynamoDB - 如何检查现有 table 是空的还是非空的

DynamoDB - how to check that an existing table is empty or non-empty

我正在尝试实现一个函数,给定 DynamoDB 和我知道数据库中存在的 table 的名称,确定此 table 是否为空。

我希望 Java 中的签名如下所示:

public Boolean isEmpty(DynamoDB database, String tableName) = ???

为了这个问题的目的,假设 table 有一个主键,由一个名为 "UserId" 的整数类型属性组成。

我知道可以使用扫描来查看 table,但我 (a) 不知道表达式会是什么样子,并且 (b) 需要对其进行限制到单个项目,这样我们就不必在非空的情况下扫描整个 table (可能很大)。

编辑:

我是否应该在构造函数中使用 AmazonDynamoDB 而不是 DynamoDB?前者有一个 scan 方法,它采用 ScanRequest - 您可以使用 .limit(1) 轻松设置限制 - 而对于后者,我会做类似 database.getTable(tableName).scan(...) 的事情,但是此扫描需要 ScanSpec,我不清楚如何为其设置限制。

我不知道Java中是怎么做的,但它必须类似于Java脚本:

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中的代码应该是相似的...如果不够清楚,请随时询问详细信息。

在回答我自己的问题时,我发现了以下内容:

我尝试使用的 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
}