简体   繁体   中英

Create a relationship between nodes based on existing relationship between the nodes

I have multiple relationships between two users that are as follow:

(u1:User)-[:BR]-(b:Buyer {value:"A"})-[:BR]-(u2:User)
(u1:User)-[:BR]-(b:Buyer {value:"B"})-[:BR]-(u2:User)
(u1:User)-[:BR]-(b:Buyer {value:"C"})-[:BR]-(u2:User)

I'd like to combine all of them into a single relationship (while keeping the old ones) between the two users, while keeping the node's value to create a list and set is as the new relationship's value like this:

(u1:User)-[:R {data:["A", "B", "C"]}]-(u2:User)

Is there any way to do this?

Edit: keywords can appear more than once.

This is my test data. I created sample data with different scenarios. The problem is u1 and u2 have non-directional relationships so you will get duplicated paths from u1 to u2 and u2 to u1.

CREATE (u1:User)
CREATE (u2:User)
CREATE (u3:User)
CREATE (ba:Buyer {value:"A"})
CREATE (bb:Buyer {value:"B"})
CREATE (bc:Buyer {value:"C"})
CREATE (bd:Buyer {value:"D"})
MERGE (u1)-[:BR]-(ba)-[:BR]-(u2)
MERGE (u1)-[:BR]-(bb)-[:BR]-(u2)
MERGE (u1)-[:BR]-(bc)-[:BR]-(u2)
MERGE (u2)-[:BR]-(bb)-[:BR]-(u3)
MERGE (u2)-[:BR]-(bd)-[:BR]-(u3)

Step1 is to ensure that u1 and u2 are not the same. Then collect distinct value and sort it by this values. Then I created a collection of all the nodes to generate a row number (called it uw or row). Then create the relationship for even rows only so that there is no duplicates. Lastly, create the relationship from u1 to u2 using values as data.

MATCH (u1:User)-[:BR]-(b:Buyer)-[:BR]-(u2:User) where u1 <> u2
WITH u1, u2, collect(distinct b.value) as v  order by v
WITH collect([u1,u2,v]) as cols 
UNWIND range(1, size(cols)) as uw 
WITH uw as row, cols[uw-1][0] as u1, cols[uw-1][1] as u2, cols[uw-1][2] as values WHERE row%2=0
MERGE (u1)-[:R {data: values}]-(u2)

Result: 在此处输入图像描述

I don't know if this is the most efficient way but I'm able to achieve this with thee following command:

match (u1:User)-[:BR]-(b:Buyers)-[:BR]-(u2:User) with u1, u2, collect(b.value) as bys merge (u1)-[:R {data:bys}]-(u2)

Edit: And then remove the duplicate relationships with:

match (u1:User {userid:"622f0137d799ed4369b077e1"})-[r:R]->(u2)-[:R]->(u1)
DELETE r

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM