How to set limit of matching items returned by DynamoDB using Java?

This is how you can limit a query result using aws-java-sdk ver 1.10.61

import com.amazonaws.AmazonClientException;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.DefaultAWSCredentialsProviderChain;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBAsyncClient;
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
import com.amazonaws.services.dynamodbv2.document.Item;
import com.amazonaws.services.dynamodbv2.document.ItemCollection;
import com.amazonaws.services.dynamodbv2.document.QueryOutcome;
import com.amazonaws.services.dynamodbv2.document.spec.QuerySpec; 



AWSCredentialsProvider provider = new DefaultAWSCredentialsProviderChain();
AmazonDynamoDBAsyncClient client = new AmazonDynamoDBAsyncClient(provider);
Region region = Region.getRegion(Regions.fromName(DYNAMODB_REGION));
client.setRegion(region);
dynamoDB = new DynamoDB(client);

QuerySpec querySpec = new QuerySpec();

/* MAX 1 item */
querySpec.setMaxResultSize(1);

querySpec.withHashKey("myPartitionKeyName", partitionKeyValue);

ItemCollection<QueryOutcome> query = dynamoDB.getTable(DYNAMODB_TABLE).query(querySpec);

You need to apply the limit as part of the request that you send to the API, not on the response.

I assume the request object you are submitting to the dynamodb object is a QuerySpec. What you will want to do is is call withMaxResultSize to pass in the limit you want applied before the query is run against the API.

However, as you mentioned in your question you need to make sure you understand the behavior of limit as described in the DynamoDB documentation on Limits:

In a response, DynamoDB returns all the matching results within the scope of the Limit value. For example, if you issue a Query or a Scan request with a Limit value of 6 and without a filter expression, DynamoDB returns the first six items in the table that match the specified key conditions in the request (or just the first six items in the case of a Scan with no filter). If you also supply a FilterExpression value, DynamoDB will return the items in the first six that also match the filter requirements (the number of results returned will be less than or equal to 6).

What this means is that if you are not using a FilterExpression you are likely fine. However, if you are filtering the results you will likely receive fewer than your limit because the limit is technically not the number of results to return rather the number of items DynamoDB could potentially return.

It sounds like you are asking for a way to have DynamoDB limit the number of results it returns to an exact number while having a FilterExpression applied. Unfortunately this is currently not possible with DynamoDB.