Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create multiple nodes with cypher in neo4j

I would like to create multiple disconnected nodes using a single cypher query

The documentation says:

Create multiple nodes with a parameter for their properties. By providing Cypher an array of maps, it will create a node for each map.

CREATE (n { props })
RETURN n

In the neo4j rest web console I tried (amongst many other things)

CREATE (n [{a:1,b:2}, {a:1,b:2}]) RETURN n

But receive this error

Invalid input '[': expected whitespace, comment, node labels, MapLiteral, a parameter, ')' or a relationship pattern (line 1, column 11) "CREATE (n [{a:1,b:2}, {a:1,b:2}]) RETURN n"

Is it possible to do what I am trying and if so how?

like image 534
rogermushroom Avatar asked Jan 12 '23 00:01

rogermushroom


2 Answers

It has to be a parameter either to the http-api or the java-api.

CREATE (n { props })
RETURN n

{props:[{a:1,b:2}, {a:1,b:2}]}

Or you can use foreach even with literal arrays

FOREACH (props IN [{ a:1,b:2 }, { a:1,b:2 }]| 
         CREATE ({ a:props.a,b:props.b }))
like image 160
Michael Hunger Avatar answered Jan 14 '23 17:01

Michael Hunger


I tried the answer from Michael Hunger, but it didnt work. Older version perhaps? I'm using 3.1.3

Here's what worked for me

UNWIND {props} AS map
CREATE (n)
SET n = map

where you need to pass {props} as the parameter to the java api

Here's a quick example in Groovy:

List<Map<String, String>> props = list.collect{ C c -> ["name": c.name] }
neo4jOperations.query("unwind {props} as map create (c) set c = map", ["props": props])
like image 41
Abbas Gadhia Avatar answered Jan 14 '23 16:01

Abbas Gadhia