2

我正在尝试对一个简单的 DynamoDB 表执行分页以按日期范围进行查询,并希望将 LastEvaluatedKey 强制转换为“hasMoreResults”布尔值以供我的前端使用,但现在看到有时会出现非空 LastEvaluatedKey即使日期范围内的项目数量不超过我的限制,也会影响结果。这是否意味着我将始终需要执行不会返回任何其他项目的后续查询?

我的桌子看起来像:

[
    {PK: "john", SK: "2021-01-01:08:00", amount: 1},
    {PK: "john", SK: "2021-01-01:20:00", amount: 2},
    {PK: "john", SK: "2021-01-02:08:00", amount: 3},
    {PK: "john", SK: "2021-01-02:20:00", amount: 4},
    {PK: "john", SK: "2021-01-03:08:00", amount: 5},
    {PK: "john", SK: "2021-01-03:20:00", amount: 6}
    ...and on for all of January
];

使用 JavaScript DocumentClient,我的查询如下所示:

async function getEntriesByDate({name, startDate, endDate, limit, sort}) {
    return await docClient.query({
        TableName: "someTableName",
        KeyConditionExpression: "#pk = :pk and #sk Between :startDate And :endDate",
        ExpressionAttributeNames: {
            "#pk": "PK",
            "#sk": "SK"
        },
        ExpressionAttributeValues: {
            ":pk": name,
            ":startDate": startDate,
            ":endDate": endDate
        },
        ScanIndexForward: sort === "asc",
        Limit: limit
    }).promise();
}

如果我调用函数的结束日期与第四项的日期完全匹配且 LIMIT 为 4:

getEntriesByDate({name: "john", startDate: "2021-01-01:08:01", endDate: "2021-01-02:20:01", limit: 4, sort:"asc"});

我得到以下结果:

{
  "Items": [
    {"PK": "john", "SK": "2021-01-01:08:00", "amount": 1},
    {"PK": "john", "SK": "2021-01-01:20:00", "amount": 2},
    {"PK": "john", "SK": "2021-01-02:08:00", "amount": 3},
    {"PK": "john", "SK": "2021-01-02:20:00", "amount": 4 }
  ],
  "Count": 4,
  "ScannedCount": 4
}

太好了,没有 LastEvaluatedKey。这是我所期望的。但是,如果我使用相同的参数调用函数,除了在结束日期添加一分钟,我会得到:

{
  "Items": <same as in last query, which is expected>,
  "Count": 4,
  "ScannedCount": 4,
  "LastEvaluatedKey": {
    "SK": "2021-01-02:20:00",
    "PK": "john"
  }
}

并且LastEvaluatedKey确实出现,即使没有满足查询的其他项目。这个问题有惯用的解决方案吗?ExclusiveStartKey为了确保可靠的值,我的函数内部是否需要后续查询(可能使用) hasMoreResults

4

0 回答 0