想象一下以下函数正在查询 GlobalSecondaryIndex 和关联的 Range Key 以查找有限数量的结果:
@Override
public List<Statement> getAllStatementsOlderThan(String userId, String startingDate, int limit) {
if(StringUtils.isNullOrEmpty(startingDate)) {
startingDate = UTC.now().toString();
}
LOG.info("Attempting to find all Statements older than ({})", startingDate);
Map<String, AttributeValue> eav = Maps.newHashMap();
eav.put(":userId", new AttributeValue().withS(userId));
eav.put(":receivedDate", new AttributeValue().withS(startingDate));
DynamoDBQueryExpression<Statement> queryExpression = new DynamoDBQueryExpression<Statement>()
.withKeyConditionExpression("userId = :userId and receivedDate < :receivedDate").withExpressionAttributeValues(eav)
.withIndexName("userId-index")
.withConsistentRead(false);
if(limit > 0) {
queryExpression.setLimit(limit);
}
List<Statement> statementResults = mapper.query(Statement.class, queryExpression);
LOG.info("Successfully retrieved ({}) values", statementResults.size());
return statementResults;
}
List<Statement> results = statementRepository.getAllStatementsOlderThan(userId, UTC.now().toString(), 5);
assertThat(results.size()).isEqualTo(5); // NEVER passes
Run Code Online (Sandbox Code Playgroud)
每当我查询数据库时,都不会遵守该限制。我总是返回与我的搜索条件匹配的所有结果,因此如果我将 设为 ,startingDate
那么now
我会获取数据库中的每个项目,因为它们都早于now
。
您应该使用queryPage
函数而不是query
.
来自DynamoDBQueryExpression.setLimit
文档:
设置对 DynamoDB 的每个服务请求中要检索的最大项目数。
请注意,调用 DynamoDBMapper.query 时,如果需要检索整个结果集,则会向 DynamoDB 发出多个请求。设置此项将限制每个请求检索的项目数,而不是限制检索的结果总数。使用 DynamoDBMapper.queryPage 从 DynamoDB 检索单页项目。
归档时间: |
|
查看次数: |
1468 次 |
最近记录: |