DynamoDB 分页 - 最后评估的键在最后一页不为空

DynamoDB pagination - last evaluated key is not null on last page

我正在尝试使用 Java SDK 在 DynamoDB 中实现分页。

我有一个简单的数据模型,其 ID 为 HashKey,日期为 RangeKey。我想查询给定日期之后的所有日期。到目前为止这是可行的,但问题是使用最后评估的键的分页部分。

查询最后一页时,lastEvaluatedKey不为null,仍指向查询的最后一页的最后一项。此键设置为 èxclusiveStartKey 然后 returns 0 的另一个查询结果为 null lastEvaluatedKey.

我的代码如下所示:

var query = new DynamoDBQueryExpression<DynamoModel>();
var keyCondition = ImmutableMap.<String, AttributeValue>builder()
        .put(":v_userid", new AttributeValue().withS(userId))
        .put(":v_date", new AttributeValue().withS(date.toString()))
        .build();

if (!StringUtils.isEmpty(lastKey)) {
    query.setExclusiveStartKey(ImmutableMap.<String, AttributeValue>builder()
            .put("userId", new AttributeValue().withS(userId))
            .put("date", new AttributeValue().withS(lastKey)).build());
}

query.withKeyConditionExpression("userId = :v_userid AND date >= :v_date");
query.withExpressionAttributeValues(keyCondition);
query.setLimit(2);

QueryResultPage<DynamoModel> resultPage = mapper.queryPage(DynamoModel.class, query);

有人知道为什么在到达匹配 KeyCondition 的最后一项时 lastEvaluatedKey 不为空吗?当我只保存符合条件的项目时,LastEvaluatedKey 按预期为空。

这是 DynamoDB 的预期行为。

If LastEvaluatedKey is not empty, it does not necessarily mean that there is more data in the result set. The only way to know when you have reached the end of the result set is when LastEvaluatedKey is empty. (source)

这是 AWS 的设计决定。我能想到的最可能的解释是,如果有更多项目,为了获得 LastEvaluatedKey,他们会不断扫描以找到更多项目,如果您使用过滤器表达式,他们可能有扫描分区的其余部分以确定是否还有更多项目。这是一个有助于最小化查询(和扫描)操作延迟的选择。