AWS Step Functions:如何过滤Map聚合结果中的空对象
AWS Step Functions Map状态:过滤聚合结果中的空对象
问题描述
我有一个类型为Map的Step Function,是否可以让聚合输出中不包含迭代的空值?若无法实现,能否直接过滤聚合结果里的空对象?还是必须通过Lambda来完成此操作?
对应的状态机片段:
"Validate-All": { "Type": "Map", "ItemsPath": "$.shippedItems", "Parameters": { "item.$": "$$.Map.Item.Value" }, "MaxConcurrency": 5, "Iterator": { "StartAt": "Validate", "States": { "Validate": { "Type": "Task", "Resource": "arn:aws:lambda:us-east-1:123456789:function:process-input", "ResultPath": "$.output", "Next": "Is input validated successfully?", }, "Is input validated successfully?": { "Type": "Choice", "Choices": [ { "Variable": "$.output.isValidatedSuccessfully", "BooleanEquals": true, "Next": "Validation Successful" }, ], "Default": "Validation Failed" }, "Validation Successful": { "Type": "Pass", "OutputPath": "$.item", // -> outputs item "End": true }, "Validation Failed": { "Type": "Pass", "Result": null, // -> outputs empty {} "End": true } } }, "ResultPath": "$.ItemsProcessedSuccessfully", // aggregate outputs from map - contains empty {} that failed and item object that succeed "End": true }, // Question: Is there a way to filter out empty {} in aggregate from map? "CreateSuccessReport": { "Type": "Task", ... "End": true }
解决方案
1. Map状态能否直接跳过空值聚合?
不行。Map状态的默认行为是保留所有迭代的输出结果,不管是验证成功的对象还是失败返回的空对象,都会被纳入最终的聚合数组里,Step Functions没有内置配置可以让Map自动过滤空值。
2. 无需Lambda,用内置状态过滤
完全可以通过Step Functions的Pass状态+JMESPath表达式实现过滤,不需要额外调用Lambda。
具体步骤:
在Validate-All状态之后、CreateSuccessReport之前新增一个Pass状态,用JMESPath筛选掉空对象:
"Filter-Successful-Items": { "Type": "Pass", "InputPath": "$", "ResultPath": "$.ItemsProcessedSuccessfully", "Parameters": { "filteredItems.$": "$.ItemsProcessedSuccessfully[?@ != `{}`]" }, "Next": "CreateSuccessReport" }
同时修改Validate-All的配置,把End: true改成Next: "Filter-Successful-Items",让状态流衔接起来。
表达式说明:[?@ != {}] 是JMESPath的过滤语法,作用是从数组中筛选出不等于空对象的元素,刚好匹配你要剔除验证失败返回的空对象的需求。
3. 什么时候需要用Lambda?
只有当你的过滤逻辑非常复杂(比如需要基于多个字段做组合判断、或者涉及数据转换),JMESPath无法满足时,才需要用Lambda来处理。当前场景下,内置的Pass状态完全足够。
内容的提问来源于stack exchange,提问作者PBandJ
相关产品推荐
相关产品推荐

