Reputation: 101
This is supposed to be a really easy task and yet I am struggling. To all the people who are expert in a graph-database and Neo4j I would really appreciate some help and make my life a bit easier. I can't seem to figure out this MERGE clause with NULL values in CSV files.
Example.csv file contains
Name,Lastname,Team,Room
AAAA,BBBB,CCCC,1111
DDDD,EEEE,FFFF,2222
GGGG,HHHH,,3333
IIII,JJJJ,KKKK,
LLLL,MMMM,CCCC,1111
NNNN,OOOO,,2222
When executing
LOAD CSV WITH HEADERS FROM 'file:///EXAMPLE.csv' AS row WITH row RETURN row
I can see some fields like Team and Room has null values. I would like to create nodes for Employees, Team and Room and here is the code I have written so far.
CREATE CONSTRAINT ON (t:Team) ASSERT t.name IS UNIQUE;
CREATE CONSTRAINT ON (r:Room) ASSERT r.name IS UNIQUE;
LOAD CSV WITH HEADERS FROM 'file:///EXAMPLE.csv' AS row WITH row WHERE row.Room <> '' AND row.Room IS NOT NULL AND row.Team <> '' AND row.Team IS NOT NULL
CREATE (m:Employee {name: toUpper(row.Lastname), firstname: toUpper(row.Name)})
MERGE (r:Room { name:row.Room})
MERGE (t.Team {name:row.Team})
CREATE (m)-[:WORKS_IN]->(r)
CREATE (m)-[:WORKS_WITH]->(t);
I guess you already guessed some entries with null values are cancelled and not taken. I want to keep the Employees within the database even it has no entries in department or team ie. no relationship exists if null.
I would really appreciate some help and many thanks in advance.
Upvotes: 2
Views: 3988
Reputation: 16365
You can try using FOREACH and CASE WHEN to handle conditions. Something like this:
CREATE (m:Employee {name: toUpper(row.Lastname), firstname: toUpper(row.Name)})
FOREACH (n IN (CASE WHEN row.Room IS NULL THEN [] ELSE [1] END) |
MERGE (r:Room { name:row.Room})
CREATE (m)-[:WORKS_IN]->(r)
)
FOREACH (n IN (CASE WHEN row.Team IS NULL THEN [] ELSE [1] END) |
MERGE (t:Team {name:row.Team})
CREATE (m)-[:WORKS_WITH]->(t)
)
The FOREACH
block will be executed only once when the related line is different of null.
Upvotes: 4