user3091744
user3091744

Reputation:

Cypher: Create node and the relation in one query

I need to create a neo4j cypher Query which first creates a node MyGroup, then a node MyDomain and at least a relation between them.

So far I;ve tried a few things and ended up with:

CREATE (p:Group { Name: "myGroup"}), (d:Domain {Name:"myDomain"}) 
WITH MATCH(g:Group {Name:"myGroup"}), (d:Domain {Name:"myDomain"}) 
CREATE(g)-[r: MEMBER_IN]->(d)

If I enter the Create and the MATCH separately, it works, but not in a combined query together with WITH?

Upvotes: 0

Views: 233

Answers (1)

Dave Bennett
Dave Bennett

Reputation: 11216

Since you already have the identifier, p for the Group and d for the Domain you don't need to re-match those objects before you create the relationship.

You could simply do this

CREATE (p:Group { Name: "myGroup"}), (d:Domain {Name:"myDomain"}) 
CREATE (p)-[r: MEMBER_IN]->(d)

Alternatively, you could create them in a single statement.

CREATE (p:Group { Name: "myGroup"})-[r: MEMBER_IN]->(d:Domain {Name:"myDomain"}) 

Or, if any or all of the items already exist and you do not want them to be recreated you could do something like the following. MERGE will either CREATE items if they do not exist or MATCH them if they do already exist.

MERGE (d:Domain {Name:"myDomain"}) 
MERGE (p:Group { Name: "myGroup"})
MERGE (p)-[r: MEMBER_IN]->(d)

Upvotes: 1

Related Questions