Jeroen Steen
Jeroen Steen

Reputation: 541

Merge node with same property value in Neo4j

When I search for nodes with a certain zipcode:

MATCH (z:ZipCode) WHERE z.zipcode = "2014 AAE" RETURN z.zipcode

I get duplicates:

z.zipcode
2014 AAE
2014 AAE

When I search for relations of a certain zipcode:

MATCH p=(z:ZipCode)-->() WHERE z.zipcode = "2014 AAE" RETURN p

I get a single zipcode node 2014 AAE pointing to a house node 518Q

How can I merge the zipcode nodes with the same property value, but leave all the relations intact of the zipcode?

Edit:

After cybersam's answer I constructed a query. Is this the way to combine the nodes with APOC?

MATCH (z1:ZipCode)-->(), (z2:ZipCode)-->()
WHERE z1.zipcode = z2.zipcode
AND ID(z1) <> ID(z2)
WITH COLLECT([z1,z2]) AS zs
CALL apoc.refactor.mergeNodes(zs) YIELD node
RETURN node;

I get this as error:

Type mismatch: expected Collection<Node> but was Collection<Collection<Node>> (line 5, column 31 (offset: 160))
"CALL apoc.refactor.mergeNodes(zs) YIELD node"

Upvotes: 2

Views: 2721

Answers (1)

cybersam
cybersam

Reputation: 67044

[UPDATED]

Aside: You have 2 nodes with the same zip code, but only one of those nodes has a relationship. This explains your results thus far.

In neo4j 3.x, you can install the APOC plugin and use the mergeNodes() procedure, which takes a collection of nodes. It merges the properties and relationships of the 2nd through last nodes onto the first node, and deletes the 2nd through last nodes.

For example:

MATCH (z:ZipCode)
WHERE z.zipcode = "2014 AAE"
WITH COLLECT(z) AS zs
CALL apoc.refactor.mergeNodes(zs) YIELD node
RETURN node;

Upvotes: 4

Related Questions