Cypher查询实现Map列表中相同name对应crud值的合并
实现方案
原生Cypher实现(无需依赖APO)
你可以通过两次UNWIND展开+去重的方式实现需求,示例代码如下:
// 替换下方inputList为你实际的列表变量即可 WITH [ {name: 'MANAGE_USERS', crud: ['READ']}, {name: 'MANAGE_SITES', crud: ['UPDATE']}, {name: 'MANAGE_USERS', crud: ['READ','DELETE']}, {name: 'MANAGE_SITES', crud: ['CREATE']} ] AS inputList // 展开列表中的每一个权限Map UNWIND inputList AS permItem // 展开每个Map下的crud权限动作 UNWIND permItem.crud AS action // 按名称+动作去重,避免重复权限 WITH DISTINCT permItem.name AS name, action // 按名称分组,收集去重后的权限为crud数组 WITH name, collect(action) AS mergedCrud // 组装为最终的List<Map>结构 RETURN collect({name: name, crud: mergedCrud}) AS result
以上代码可以直接匹配你给出的两个示例输入,输出完全符合预期,且不依赖任何APO扩展函数。
APO简化实现
如果你允许使用APO函数,可以用集合处理函数简化分组后的数组合并逻辑:
WITH $yourInputList AS inputList UNWIND inputList AS permItem WITH permItem.name AS name, collect(permItem.crud) AS crudLists // flatten拍平嵌套数组,toSet自动去重 WITH name, apoc.coll.toSet(apoc.coll.flatten(crudLists)) AS mergedCrud RETURN collect({name: name, crud: mergedCrud}) AS result
内容的提问来源于stack exchange,提问作者Lorenzo Valente
相关产品推荐
相关产品推荐

