Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cypher query to create multiple nodes and relationships

I'm trying to write a Cypher query to create multiple nodes and relationships in one query. The documentation on using CREATE clauses in Cypher states that it's not possible to create multiple nodes of different types in a singular CREATE clause.

However it hints that I should be able to break it up into multiple CREATE's. A couple of similar answers I have read point to the same solution as well. I've tried doing this and keep getting the response error.

Error: If you create multiple elements, you can only create one of each.

Here is a brief outline of what I'm trying to do.

  1. Create an item node.
  2. Create multiple representation nodes.
  3. Create a relationship between the created item node and an existing stack node.
  4. Create multiple relationships between the created item node and the created representation nodes.

This is the query I'm currently using which attempts to break up all the individual parts of the CREATE process into individual steps.

START stack=node({stack})
CREATE (item {item}) 
CREATE (representations {representations})
CREATE (stack)-[:Item]->(item)
CREATE (item)-[:Representation]->(representations)
RETURN item, representations

I've tried several variations of the above query, including putting the creation of the item and representation nodes at the beginning of the query.

I would really appreciate any advice. I really don't want to resort to making multiple database calls if it can be avoided.

like image 588
AshHeskes Avatar asked Mar 10 '14 15:03

AshHeskes


1 Answers

Is your representations a list ? Then you can only have that as the single create statement.

I assume Neo4j 1.9 from your syntax.

What you can do though is to use FOREACH

START stack=node({stack})
CREATE (item {item}) 
CREATE (stack)-[:Item]->(item)
FOREACH (r in {representations} : 
   CREATE (representation {r}), (item)-[:Representation]->(representation)
)
MATCH (item)-[:Representation]->(representations)
RETURN item, representations
like image 94
Michael Hunger Avatar answered Oct 05 '22 12:10

Michael Hunger