3
votes

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?

3

3 Answers

6
votes

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 }))
2
votes

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])
0
votes

First, a disclaimer: I am not an expert on Neo4j, but just an unexperienced graph enthusiast. I'm using Neo4j Browser version: 4.0.1 + Neo4j Server version: 3.5.12 (enterprise).

After unsuccessfully trying a million recipes from the internet, I finally realised that none of them will work unless you type them independently on Neo4j Desktop query editor!

Alternatively, you could type a semicolon (';') after each cypher statement, if you want to keep all statements in the same query window. In such case, you need to allow multi statements, ticking on Neo4j Browser settings > Enable multi statement query editor.

So, to make it explicit and easier for newbies like me, here we have a working example.

Initially, in the query editor, type:

:param props => [{name: 'John', age: 18}, {name: 'Phill', age: 23}]

This will save the above parameters in your system under the object props as:

{
"props": [
{
  "name": "John",
  "age": 18
},
{
  "name": "Phill",
  "age": 23
}
]
}

Then, in a BRAND NEW query editor window, type:

FOREACH (props IN $props | CREATE (a {name:props.name, age:props.age}))

and hopefully, you will get the msg:

Created 2 nodes, set 2 properties, completed after 7 ms.

Then, in order to flush these parameters from your system, so that they do not interfere with any further ones, type:

:params {}