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

jbwheatley :

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.

jbwheatley :

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
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=107141&siteId=1