You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

已知用+替代apoc.coll.unionAll,如何用纯Cypher实现apoc.coll.union?

纯Cypher实现列表去重并集(替代apoc.coll.union)

已知纯Cypher中可通过+运算符替代apoc.coll.unionAll,示例语句:

WITH [1,2] as list1, [1,2,3,4] as list2 
WITH list1 + list2 as list3 

要实现apoc.coll.union的去重并集效果,纯Cypher可通过以下两种方式完成:

方法一:简单去重(不严格保证顺序)

通过合并列表、展开元素、去重后重新收集:

WITH [1,2] as list1, [1,2,3,4] as list2
UNWIND list1 + list2 AS item
WITH DISTINCT item
COLLECT(item) AS unionList

方法二:保留元素首次出现顺序(与apoc.coll.union行为一致)

如果需要和apoc.coll.union一样,保留元素第一次出现的顺序,可通过记录元素索引实现:

WITH [1,2] as list1, [1,2,3,4] as list2
UNWIND list1 + list2 AS item
WITH item, INDEX(list1 + list2, item) AS idx
WITH item, MIN(idx) AS firstOccurrenceIdx
ORDER BY firstOccurrenceIdx
COLLECT(item) AS unionList

注意点

  • 方法一实现简单,但最终列表的元素顺序可能和原列表合并后的顺序有差异;
  • 方法二严格遵循apoc.coll.union的行为:优先保留第一个列表的元素顺序,再追加第二个列表中未出现过的元素。

内容的提问来源于stack exchange,提问作者alexanoid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 00:53:22