I have a DynamoDB table that has a partition key and a sort key.
In my Java code I need to get one (and only one) record with a partition key if that record exists.
Currently I am using DynamoDB V2 Enhanced SDK and I do this by getting ALL records that match this partition key.
However, if there are lots of records (say, 100,000) with the same partition key, the query could take quite long, when in fact I only need one record and not the rest of queried items(say, 99,999 items) .
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable;
import software.amazon.awssdk.enhanced.dynamodb.Key;
import software.amazon.awssdk.enhanced.dynamodb.model.GetItemEnhancedRequest;
import software.amazon.awssdk.enhanced.dynamodb.model.QueryConditional;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
public MyFooEntity getOneItemByPartitionKey(String partitionKey) {
AttributeValue pk = AttributeValue.builder().s(partitionKey).build();
List<MyFooEntity> fooList = super.getAllByKey(table, pk);
return fooList.size() > 0 ? fooList.get(0) : null;
}
protected List<E> getAllByKey(DynamoDbTable<E> table, AttributeValue partitionKey) {
Key key = Key.builder().partitionValue(partitionKey).build();
QueryConditional queryCond = QueryConditional.keyEqualTo(key);
List<E> resultList = table.query(queryCond).items().stream().collect(Collectors.toList());
return resultList;
}
I tried to limit the query result but it did not work. Same amount of records (100,000) will be returned.
List<E> resultList = table.query(queryCond).limit(1).items().stream().collect(Collectors.toList());
return resultList;
}
I hope to do a query that, as soon as the first record with the same partition key is found, the result list is returned immediately.