使用 Node.js 在 DynamoDB 中进行分页?

新手上路,请多包涵

我已经阅读了 AWS 的关于 pagination 的文档

正如他们的文档所指定的:

在响应中,DynamoDB 返回限制值范围内的所有匹配结果。例如,如果您发出限制值为 6 且没有过滤器表达式的 Query 或 Scan 请求,则 DynamoDB 会返回表中与请求中指定的键条件匹配的前六个项目(或仅返回表中的前六个项目)。没有过滤器的扫描的情况)

Which means that given I have a table called Questions with an attribute called difficulty (that can take any numeric value ranging from 0 to 2 ) 我可能会遇到以下难题:

  • 客户提出请求,认为 GET /questions?difficulty=0&limit=3
  • 我将 3 转发给 DynamoDB 查询,它可能会返回 0 项目作为集合中的前 3 个可能不是 difficulty == 0
  • 然后我必须执行一个新查询来获取更多符合该条件的 questions 而不知道我可能会返回重复项

然后如何根据查询正确分页?在获得正确偏移量的同时,我会得到尽可能多的结果

原文由 user2061811 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 695
1 个回答

使用异步/等待。

 const getAllData = async (params) => {

    console.log("Querying Table");
    let data = await docClient.query(params).promise();

    if(data['Items'].length > 0) {
        allData = [...allData, ...data['Items']];
    }

    if (data.LastEvaluatedKey) {
        params.ExclusiveStartKey = data.LastEvaluatedKey;
        return await getAllData(params);

    } else {
        return data;
    }
}

我正在使用全局变量 allData 来收集所有数据。

调用此函数包含在 try-catch 中

try {

        await getAllData(params);
        console.log("Processing Completed");

        // console.log(allData);

    } catch(error) {
        console.log(error);
    }

我在 Lambda 中使用它,它工作正常。

这里 的文章确实帮助和指导了我。谢谢。

原文由 Roshan Khandelwal 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题