Cypher:类似于`sort -u`来合并2个集合?

时间:2014-12-09 10:47:21

标签: neo4j cypher

假设我有一个属性中有集合的节点,比如说

START x = node(17) SET x.c = [ 4, 6, 2, 3, 7, 9, 11 ];

和某处(即来自.csv文件)我得到另一个值集合,比如说

c1 = [ 11, 4, 5, 8, 1, 9 ]

我将我的收藏仅仅视为集合,元素的顺序无关紧要。我需要的是将x.c与c1合并为魔术操作,以便生成的x.c将仅包含来自两者的不同元素。我想到了以下想法(尚未经过测试):

LOAD CSV FROM "file:///tmp/additives.csv" as row
START x=node(TOINT(row[0]))
MATCH c1 = [ elem IN SPLIT(row[1], ':') | TOINT(elem) ]
SET
x.c = [ newxc IN x.c + c1 WHERE (newx IN x.c AND newx IN c1) ];

这不会起作用,它会给出一个交集但不是一系列不同的项目。 更多RTFM给出了另一个想法:使用REDUCE()?但是如何?

如何使用新的内置函数UNIQUE()扩展Cypher,它接受收集和返回集合,清理表单重复?

UPD。似乎FILTER()函数是接近但又交叉的东西:(

x.c = FILTER( newxc IN x.c + c1 WHERE (newx IN x.c AND newx IN c1) )

WBR, 安德里

3 个答案:

答案 0 :(得分:4)

这样的事情怎么样......

with [1,2,3] as a1
, [3,4,5] as a2
with a1 + a2 as all
unwind all as a
return collect(distinct a) as unique

添加两个集合并返回不同元素的集合。

2014年12月15日 - 这是对我的回答的更新......

我从neo4j数据库中的一个节点开始......

//create a node in the DB with a collection of values on it
create (n:Node {name:"Node 01",values:[4,6,2,3,7,9,11]}) 
return n

我创建了一个包含两列的csv示例文件...

Name,Coll
"Node 01","11,4,5,8,1,9"

我创建了一个LOAD CSV语句......

LOAD CSV 
WITH HEADERS FROM "file:///c:/Users/db/projects/coll-merge/load_csv_file.csv" as row

// find the matching node 
MATCH (x:Node) 
WHERE x.name = row.Name

// merge the collections
WITH x.values + split(row.Coll,',') AS combo, x

// process the individual values
UNWIND combo AS value

// use toInt as the values from the csv come in as string
// may be a better way around this but i am a little short on time
WITH toInt(value) AS value, x

// might as well sort 'em so they are all purdy
ORDER BY value
WITH collect(distinct value) AS values, x
SET x.values = values

答案 1 :(得分:2)

您可以像这样使用reduce:

with [1,2,3] as a, [3,4,5] as b
return reduce(r = [], x in a + b | case when x in r then r else r + [x] end)

答案 2 :(得分:1)

自Neo4j 3.0以来,使用APOC Procedures您可以使用apoc.coll.union()轻松解决此问题。在3.1+中它是一个函数,可以像这样使用:

...
WITH apoc.coll.union(list1, list2) as unionedList
...