Cezar Sas
Cezar Sas

Reputation: 306

Copy relations from another node

I have two nodes of type User that are linked to one or more common nodes of type Tweet. An example in the image:

enter image description here

I would like to remove the duplicate users and merge them into a single node. preserving all the relations from both users.

This is the condition i use to find the nodes that needs to be merged:

MATCH (x:User)-[k:POSTS]->(:Tweet)<-[:POSTS]-(y:User)

With the following query:

  MATCH (x:User)-[k:POSTS]->(:Tweet)<-[:POSTS]-(y:User)
DELETE k
WITH x, y
MATCH (x)-[r:POSTS]->(z:Tweet)
MERGE (y)-[:POSTS]->(z)
DELETE r

which detach user_b but don't link the tweet to user a.

Note that i tried also apoc.refactor.mergeNodes, but it gives error.

How can i merge these two nodes preserving their releationships?

UPDATE:

MATCH (z:User)
WHERE (z:User)-[:POSTS]->(:Tweet)<-[:POSTS]-(:User) 
WITH COLLECT(z) AS zs
CALL apoc.refactor.mergeNodes(zs) YIELD node
RETURN node;

With this query i obtain duplicate relations, is there a way to merge?

UPDATE 2:

I tried to use the previous query on a larger sample of my database, it gives error.

Upvotes: 1

Views: 161

Answers (1)

stdob--
stdob--

Reputation: 29172

This query first delete relation from (x) to (tweet) and then try find it.

Try this:

MATCH (x:User)
WITH x
MATCH (x)-[:POSTS]->(t:Tweet)<-[r:POSTS]-(y:User) WHERE x <> y AND id(x) > id(y)
WITH x, y, count(t) as ag
MATCH (y)-[r:POSTS]->(z:Tweet)
MERGE (x)-[:POSTS]->(z)
WITH y, count(z) as ag
DETACH DELETE y

Upvotes: 1

Related Questions