.NET Core 7中如何用ScanFilter实现DynamoDB多OR条件扫描?
如何用多个OR条件执行DynamoDB扫描操作
你当前的代码中,ScanFilter默认会将多个添加的条件视为AND逻辑,也就是要求property1和property2同时不为空,这不符合你需要的OR需求。要实现OR条件,可按以下方式处理:
方法1:使用旧版ScanFilter实现OR逻辑
在旧版AWS SDK for .NET中,需将多个子条件封装到一个Condition中,指定其逻辑运算符为Operator.Or,再将组合条件添加到ScanFilter:
ScanFilter prodFilter = new ScanFilter(); // 创建OR组合条件 Condition orCondition = new Condition { Operator = Operator.Or, ConditionList = new List<Condition> { new Condition { AttributeName = "property1", Operator = ScanOperator.IsNotNull }, new Condition { AttributeName = "property2", Operator = ScanOperator.IsNotNull } } }; prodFilter.AddCondition(orCondition); Search search = prodTable.Scan(prodFilter);
方法2:使用推荐的FilterExpression(更优)
注意:ScanFilter已被AWS标记为过时,官方推荐使用FilterExpression结合内置函数构建过滤条件,这种方式更灵活且符合最新API规范:
var scanRequest = new ScanRequest { TableName = prodTable.TableName, FilterExpression = "attribute_exists(property1) OR attribute_exists(property2)" }; var scanResponse = prodTable.Scan(scanRequest);
这里的attribute_exists()是DynamoDB内置函数,作用等同于IsNotNull,用于判断属性是否存在。若属性名包含特殊字符,可通过ExpressionAttributeNames替换:
var scanRequest = new ScanRequest { TableName = prodTable.TableName, FilterExpression = "attribute_exists(#p1) OR attribute_exists(#p2)", ExpressionAttributeNames = new Dictionary<string, string> { { "#p1", "property1" }, { "#p2", "property2" } } }; var scanResponse = prodTable.Scan(scanRequest);
内容的提问来源于stack exchange,提问作者khteh
相关产品推荐
相关产品推荐

