6
votes

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.

1
Which API are you using to execute cypher, the embedded Java or some REST driver/client?jjaderberg
@jjaderberg I'm using a the nodejs neo4j client which is a REST client.AshHeskes

1 Answers

5
votes

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