cancel
Showing results for 
Search instead for 
Did you mean: 

Head's Up! These forums are read-only. All users and content have migrated. Please join us at community.neo4j.com.

How to create records in foreach without repeating the properties

I am brand new to Cypher and just learning. The query below works and creates the records I want, but it seems unnecessary to repeat all of the properties in the CREATE statement:

WITH [
	{id: 1, name: "Gold"}, 
	{id: 2, name: "Banking"},
	{id: 3, name: "Canada"},
	{id: 4, name: "T.BMO", parentId: 2},
	{id: 5, name: "Opinion"},
	{id: 6, name: "BC", parentId: 3}
] AS tags
FOREACH (tag in tags | CREATE (:Tag{id: tag.id, name: tag.name, parentId: tag.parentId}))

I think it should be possible to write something like this instead, but I can't find the answer from the documentation:

WITH [
	{id: 1, name: "Gold"}, 
	{id: 2, name: "Banking"},
	{id: 3, name: "Canada"},
	{id: 4, name: "T.BMO", parentId: 2},
	{id: 5, name: "Opinion"},
	{id: 6, name: "BC", parentId: 3}
] AS tags
FOREACH (tag in tags | CREATE (tag:Tag))
1 ACCEPTED SOLUTION

You can simplify this as

WITH [
       {id: 1, name: "Gold"},
       {id: 2, name: "Banking"},
       {id: 3, name: "Canada"},
       {id: 4, name: "T.BMO", parentId: 2},
       {id: 5, name: "Opinion"},
       {id: 6, name: "BC", parentId: 3}
       ] AS tags
       FOREACH (tag in tags | CREATE (n:Tag) set n=tag);

which will create the following nodes

neo4j> match (n:Tag) return n;
+--------------------------------------------+
| n                                          |
+--------------------------------------------+
| (:Tag {name: "Gold", id: 1})               |
| (:Tag {name: "Banking", id: 2})            |
| (:Tag {name: "Canada", id: 3})             |
| (:Tag {name: "T.BMO", id: 4, parentId: 2}) |
| (:Tag {name: "Opinion", id: 5})            |
| (:Tag {name: "BC", id: 6, parentId: 3})    |
+--------------------------------------------+

6 rows available after 30 ms, consumed after another 31 ms

View solution in original post

1 REPLY 1

You can simplify this as

WITH [
       {id: 1, name: "Gold"},
       {id: 2, name: "Banking"},
       {id: 3, name: "Canada"},
       {id: 4, name: "T.BMO", parentId: 2},
       {id: 5, name: "Opinion"},
       {id: 6, name: "BC", parentId: 3}
       ] AS tags
       FOREACH (tag in tags | CREATE (n:Tag) set n=tag);

which will create the following nodes

neo4j> match (n:Tag) return n;
+--------------------------------------------+
| n                                          |
+--------------------------------------------+
| (:Tag {name: "Gold", id: 1})               |
| (:Tag {name: "Banking", id: 2})            |
| (:Tag {name: "Canada", id: 3})             |
| (:Tag {name: "T.BMO", id: 4, parentId: 2}) |
| (:Tag {name: "Opinion", id: 5})            |
| (:Tag {name: "BC", id: 6, parentId: 3})    |
+--------------------------------------------+

6 rows available after 30 ms, consumed after another 31 ms