如何在Dynamoose中按指定索引的rangeKey排序查询结果?
解决Dynamoose查询自定义索引时按指定字段排序的问题
你的问题出在索引的定义方式上,导致查询时没有正确使用c作为排序键。以下是修正方案:
1. 修正Schema的索引定义
把c字段的内联索引配置移到Schema的indexes数组中,明确定义本地二级索引(LSI)——LSI的哈希键会自动和主表保持一致(即a),排序键设为c:
const dynamoose = require("dynamoose"); const schema = new dynamoose.Schema( { a: { type: Number, required: true, hashKey: true, }, b: { type: String, required: true, rangeKey: true, // 主表默认排序键 }, c: { type: String, required: true, } }, { indexes: [ { name: "c-index", type: "local", rangeKey: "c", // 索引的排序键为c project: true, throughput: "ON_DEMAND" } ] } );
2. 调整查询代码
使用修正后的索引查询时,DynamoDB默认会按索引的排序键c升序返回结果;如果需要降序,只需添加.sort("descending"):
// 默认按c升序排序 const result = await sometingModel.query("a") .eq(a) .using("c-index") .where("c") .ge(c) .exec(); // 按c降序排序 const resultDesc = await sometingModel.query("a") .eq(a) .using("c-index") .where("c") .ge(c) .sort("descending") .exec();
原因说明
DynamoDB的本地二级索引(LSI)会复用主表的哈希键,仅用指定字段作为排序键。当你通过该索引查询时,默认会按索引的排序键排序。之前的内联索引定义方式可能导致Dynamoose没有正确识别索引的排序键配置,从而 fallback 到主表的排序键b。
内容的提问来源于stack exchange,提问作者newJin
相关产品推荐
相关产品推荐

