How to create a new node that is in relationship with the first node that has the same label?

Viewed 80

I am playing with Neo4j and Cypher, however, I ran into a problem that I couldn't solve yet. Let's say we have a node like this: (p:Person{name: "Joe"})

Then, I would add a new Person node to my database which too had a name: "Joe" property. I would like to create a relationship between the first Person Joe and the new Person Joe (and only between them!). So far I've tried the following query, which is not getting what I want:

 MATCH (p1:Person)
 WHERE p1.name = "Joe" 
 CREATE (p2:Person{name:"Joe"})-[r:SAME_NAME]->(p1))

The problem now is that it's kind of recursively creating new nodes. How can I achieve the desired query?

2 Answers

Have a nice playing!

// create initial nodes
WITH ['Joe', 'Ken', 'Lou'] AS names, [1,2,3,4,5] AS ids
UNWIND names AS name 
UNWIND ids AS id
CREATE(p:Person{name:name, id:id})
RETURN p
;

// create new 'same name' nodes with relationship
MATCH(p:Person)
WITH COLLECT(p) AS persons
UNWIND persons AS person
CREATE(p:Person{
      name: person.name
    , id:   person.id + 100
})-[:SAME_NAME]->(person)
RETURN *

Create does not care if the node exists already. Unless you have unique index, it will create a new node. Try below query;

MATCH (p:Person) WHERE p.name = "Jose"
//collect all persons with name: Jose
WITH collect(p) as persons
//for every jose in the collection persons, pick the first jose and  do a connection to every other jose in the list
FOREACH (i in range(0, size(persons) - 2) |
 FOREACH (node1 in [persons[i]] |
  //this is the other jose on the list
  FOREACH (node2 in [persons[i+1]] |
   CREATE (node1)-[:SAME_NAME]->(node2))))

FOREACH is like a for loop and we iterate on the list then create the relationship.

Related