Multiple line execution in Neo4j

Viewed 1628

I am trying to execute the following cypher code:

// Nodes created for Lessons, Submitter, Center and Topic
// Relations created 
// Uniqueness constraints.
CREATE CONSTRAINT ON (l:Lesson) ASSERT l.name IS UNIQUE;
// Load.
USING PERIODIC COMMIT
LOAD CSV WITH HEADERS FROM
'file:///llis.csv' AS line
WITH line, SPLIT(line.LessonDate, '-') AS date
CREATE (lesson:Lesson { name: TOINT(line.`LessonId`) } )
SET lesson.year = TOINT(date[0]),
    lesson.month = TOINT(date[1]),
    lesson.day = TOINT(date[2]),
    lesson.title = (line.Title),
    lesson.abstract = (line.Abstract),
    lesson.lesson = (line.Lesson),
    lesson.org = (line.MissionDirectorate),
    lesson.safety = (line.SafetyIssue),
    lesson.url = (line.url)

However, I cannot do this in the browser because it's two separate lines. See error:

Node(562) already exists with label Lesson and property name = 0

I know I am meant to do this in the Neo4j-shell. I have managed to get in to the Neo4j-shell but how do I run this bit of code there?

2 Answers

Put your syntax in a file and then run it as follows :

on Windows

type yourfile.cypher | bin\cypher-shell.bat -u <user> -p <password>

on Linux

cat yourfile.cypher | bin/cypher-shell -u <user> -p <password>

Hope this helps, Tom

Your CSV data probably has multiple rows with the same LessionId value. If so, that would cause a uniqueness constraint violation on Lesson(name) each time your CREATE clause tries to create a second Lesson node with the an existing name.

The following version of your LOAD CSV query uses MERGE instead of CREATE to avoid duplicating Lesson nodes:

USING PERIODIC COMMIT
  LOAD CSV WITH HEADERS FROM 'file:///llis.csv' AS line
WITH line, SPLIT(line.LessonDate, '-') AS date
MERGE (lesson:Lesson { name: TOINT(line.LessonId) } )
ON CREATE SET
    lesson.year = TOINT(date[0]),
    lesson.month = TOINT(date[1]),
    lesson.day = TOINT(date[2]),
    lesson.title = (line.Title),
    lesson.abstract = (line.Abstract),
    lesson.lesson = (line.Lesson),
    lesson.org = (line.MissionDirectorate),
    lesson.safety = (line.SafetyIssue),
    lesson.url = (line.url);

The above query also uses ON CREATE to only perform the SET operation if the MERGE had actually created a node. This effectively causes the query to ignore all lines in the CSV file that repeat a previously seen LessonId. If, for some reason, you actually do want the SET to always happen (even for rows with a repeated LessonId value), you can omit ON CREATE.

Related