如何配置EventBridge规则筛选StoreProducts数组非空的事件
EventBridge规则匹配非空数组配置方案
问题场景
现有结构如下的EventBridge事件,需要配置事件规则,仅当detail.data.new.StoreProducts数组非空时触发规则:
{ "version": "0", "id": "816c9de5-517b-a18a-1190-e3e3c2f51f92", "detail-type": "ProductTableEvent", "source": "pi-data", "account": "751354400372", "time": "2022-07-07T05:58:26Z", "region": "eu-west-1", "resources": [], "detail": { "data": { "new": { "Gtin": "01234567", "NoIngredientsNeeded": 1, "DeliveryCostIncluded": 0, "MaximumOrder": 0, "ProductSegment": "Vardag", "StoreProducts": [] } } } }
之前尝试编写的规则存在语法错误、匹配逻辑不符合EventBridge规则设计的问题,无法正常生效:
InsertProductRule: Type: 'AWS::Events::Rule' Properties: EventBusName: commerce EventPattern: source: - "my-source" detail # 此处漏写冒号,属于YAML语法错误 data: new: StoreProducts: - exists: true - anything-but: [] # 该写法无法实现空数组过滤
正确配置方法
EventBridge针对数组字段的匹配逻辑为:遍历数组内所有元素,只要存在任意一个元素匹配规则中定义的模式,即判定为匹配成功;如果数组为空,没有可遍历的元素,自然不会命中任何数组匹配规则。
利用这个特性,不需要使用anything-but做特殊判断,只需要给StoreProducts字段配置存在性校验即可自动过滤空数组场景,正确的CloudFormation配置如下:
InsertProductRule: Type: 'AWS::Events::Rule' Properties: EventBusName: commerce EventPattern: source: - "pi-data" # 替换为实际使用的source值 detail-type: - "ProductTableEvent" detail: data: new: StoreProducts: - exists: true
该配置的匹配逻辑:
- 要求
StoreProducts字段本身存在 - 空数组
[]没有元素可匹配exists: true的规则,会被直接过滤 - 数组长度≥1时,只要有元素存在就会命中规则,完全满足非空触发的需求
如果业务场景允许StoreProducts字段不存在,只需要去掉exists: true配置,保留空的规则列表即可。
内容的提问来源于stack exchange,提问作者Chathuri Gunawardhana
相关产品推荐
相关产品推荐

