sprint_6
sprint_6

Reputation: 81

MERGE with UNWIND Issue Neo4j

I have a list of dictionaries I have created in python. It looks like this:

[{name: 'Bob'}, {name: 'Teresa'}, {name: 'Bob'}, {name: 'Teresa'}]

Here's my cypher query to take this list and merge into Neo4j that I'm expecting only 2 new nodes are created, Bob and Teresa nodes.

WITH $batch AS batch
UNWIND batch as ind
MERGE (n:Friend)
SET n += ind

What I'm seeing is that I only see 1 node that's written to Neo4j and it seems like it's whatever the last item in the list. In this example, Teresa node is the only one that got created.

How should I fix my query so that I see Bob AND Teresa nodes created once it finishes running? Is it better practice to make the list unique [{name: 'Bob'}, {name: 'Teresa'}] and use CREATE instead of MERGE instead?

Upvotes: 0

Views: 1053

Answers (1)

Rajendra Kadam
Rajendra Kadam

Reputation: 4052

Merge requires a field(s) which you need to be unique like name in this case. If you don’t provide it then it will create only one node and add the values of the last node.

You can modify your code as below if name is the only property.

WITH $batch AS batch
UNWIND batch as ind
MERGE (n:Friend{name: ind.name})

In case there are more properties:

WITH $batch AS batch
UNWIND batch as ind
MERGE (n:Friend{name: ind.name})
SET n += ind

Upvotes: 2

Related Questions