Dynamoose使用GSI查询报索引不存在、缺失键schema元素错误如何解决?
问题原因与解决方法
报错根因
两次查询报错分别对应两个错误:
- 第一次查询将索引名
SKIndex写在了where条件中,而非索引对应的哈希键字段名SK,导致Dynamoose无法匹配到对应的索引 - 第二次查询虽然指定了使用
SKIndex,但没有显式声明要匹配索引的哈希键SK,生成的最终查询请求仅包含排序键location的条件,不符合DynamoDB查询规则:无论查询主表还是GSI,都必须先提供哈希键的等值匹配条件,才能补充排序键条件,你贴出的query:request日志也能验证这一点,KeyConditionExpression中只有location的匹配逻辑,完全缺失SK的条件。
正确查询代码
写法1(链式调用,推荐)
const SKIndex_search = "some value" const locality = "some value too" const getResult = await Seller.query("SK") .eq(SKIndex_search) .where("location").beginsWith(locality) .using("SKIndex") .exec()
写法2(Condition对象写法)
const SKIndex_search = "some value" const locality = "some value too" const filter = new dynamoose.Condition() .where("SK").eq(SKIndex_search) .where("location").beginsWith(locality) const getResult = await Seller.query(filter) .using("SKIndex") .exec()
排查要点
where方法内传入的永远是字段名,索引名仅需在using方法中传入- 所有GSI查询必须包含GSI哈希键的等值匹配条件,不能仅用排序键查询
- 可开启Dynamoose的请求日志,对比生成的查询结构是否符合预期,正常请求的
KeyConditionExpression会同时包含SK的等值匹配和location的前缀匹配逻辑
内容的提问来源于stack exchange,提问作者imin
相关产品推荐
相关产品推荐

