@aws/dynamodb-data-mapper的QueryOptions中filter如何写ConditionExpression?
问题原因
你出现类型报错的核心原因有两点:
- 构造
contains条件时没有用正确的属性引用方式指代表字段,直接传入了未定义的ProductCategory变量 - 未配套使用DataMapper官方的表达式构造工具正确生成符合要求的
ConditionExpression类型对象
解决步骤
1. 导入配套的表达式构造工具
首先确保你已经安装了@aws/dynamodb-expressions依赖,然后在代码头部导入需要的方法:
import { between, contains, attr } from '@aws/dynamodb-expressions';
2. 修改filter字段的写法
用attr('字段名')指代你要操作的表属性,单个过滤条件可直接传入contains的返回结果:
const paginator = dbMapper.query( Products, { Id: 456, Price: between(500, 1000) }, { indexName: 'indexByPriceId', limit: 10, scanIndexForward: false, filter: contains(attr('ProductCategory'), 'goods') } );
多过滤条件的写法
如果需要组合多个过滤条件,用and方法拼接即可:
import { between, contains, attr, and } from '@aws/dynamodb-expressions'; // 省略其他代码 filter: and( contains(attr('ProductCategory'), 'goods'), attr('Price').lt(800) )
注意事项
contains对字符串类型字段匹配时区分大小写,你示例中ProductCategory的值为Sporting Goods,搜索小写的goods无法命中,需要注意大小写匹配逻辑。- 过滤条件是在索引查询完成之后才执行的,
limit参数限制的是索引匹配的结果数量,不是过滤后的返回数量,注意和业务预期是否对齐。
内容的提问来源于stack exchange,提问作者Satyaki Mukherjee
相关产品推荐
相关产品推荐

