1
votes

I have been pushing several times the same relationship between 2 nodes in Neo4j. It was a mistake as it makes the visualization less clear.

Now, I would like to replace those several relations between 2 nodes by one single relation. It would be great if we could keep the number of relations inside a property "count" on the new unique relation.

What would be an efficient way to solve this problem ? I have about 100 000 of relations and I am a bit worried about the time it would take.

Here is a quick example to make the problem clearer : I have :

Node A -- R1 -- Node B
Node A -- R2 -- Node B

And I would like to have

Node A -- R {count : 2} -- Node B

Thanks!

1
I assume you want to run this over all the nodes in the database. Do these relationships have any properties on them? - Rajendra Kadam
Does the direction of relationship matters to you? What if there are X number of relationships from node A to B, and Y number of relationships from node B to A? - Rajendra Kadam

1 Answers

2
votes

I assume these relationships don't have any properties and Direction of the relationships doesn't matter.

You can combine these relationships with Cypher Query as shown:

MATCH (p:Node)-[r]-(c:Node)
WHERE ID(p) > ID(c)
DELETE r
WITH p, c, COUNT(r) as count
CREATE (p)-[:R{count:count}]->(c)

If you want to merge relationships having the same directions only then you can use the following query:

MATCH (p:Node)-[r]->(c:Node)
DELETE r
WITH p, c, COUNT(r) as count
CREATE (p)-[newrel:R{count:count}]->(c)

If you want to merge the properties as well then you can take help of apoc plugin's apoc.refactor.mergeRelationships method.