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

Viewed 1824

I am trying to implement a function that given a DynamoDB and the name of a table I know exists in the database, determines whether this table is empty or not.

I expect the signature to look like the following in Java:

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

Assume for the purposes of this question that the table has a primary key consisting of a single Integer type attribute called "UserId".

I'm aware that one can use a scan to look at a table, but I (a) don't know what the expression would look like, and (b) need it to be limited to a single item, so that we don't have to scan the entire table (which may be large) in the case that it is non-empty.

EDIT:

Should I perhaps be using an AmazonDynamoDB in my constructor instead, rather than a DynamoDB? The former has a scan method which takes a ScanRequest - for which you can easily set a limit using .limit(1) - whereas for the latter I would do something like database.getTable(tableName).scan(...), but this scan takes a ScanSpec for which it is not clear to me how to set a limit for.

2 Answers

In answer to my own question, I found the following: Difference between AmazonDynamoDBClient and DynamoDB classes in their java SDK?

The DynamoDB I was trying to use is simply a wrapper around AmazonDynamoDB that provides a slightly different API. Using the AmazonDynamoDB instead makes the implementation of this function a lot easier, and it should look something like this (please excuse bad Java code, I'm actually writing this in Scala):

public Boolean isEmpty(AmazonDynamoDB database, String tableName) = {
   ScanRequest scanRequest = new ScanRequest().withTableName(tableName).withLimit(1);
   return database.scan(scanRequest).getCount == 0;
}

Or, in Scala:

def isEmpty(database: AmazonDynamoDB, tableName: String): Boolean = {
   val scanRequest = new ScanRequest().withTableName(tableName).withLimit(1)
   database.scan(scanRequest).getCount == 0
}

I do not know how to do it in Java, but it must be similar to 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

In Java the code should be similar... feel free to ask for details it is not clear enough.

Related