Friday, June 13, 2025

The nuances of Cypher queries - the magic of semicolons

Give a comparison between below two 

Below does not work

===================

CREATE (chen:Person {name: 'Mr. David Chen'})

SET chen.title = 'Chief Technology Officer' 

CREATE (reed:Person {name: 'Dr. Evelyn Reed'})

CREATE (reed)-[:REPORTS_TO]->(chen);


Below works 

=============

CREATE (chen:Person {name:'Mr. David Chen', title:'Chief Technology Officer'})

CREATE (reed:Person {name:'Dr. Evelyn Reed'})

CREATE (reed)-[:REPORTS_TO]->(then);


This fails most likely because of a syntax or session/transaction handling issue. Let’s examine common causes:


🔍 1. Use of Semicolon (;)

Cypher doesn’t always support semicolons inside a multi-statement script, depending on the environment you’re using (e.g., Neo4j Browser, cypher-shell, or a driver).

If you’re running this as a script or block of statements, the semicolon prematurely ends the transaction, and so the variable chen no longer exists in scope for the last line:

SET chen.title = 'Chief Technology Officer';  // <- Ends the statement

after this, the next CREATE starts a new statement, and chen is undefined.

Fixing options are:

Option 1: Remove the semicolons (if not required by your tool)
CREATE (chen:Person {name: 'Mr. David Chen'})
SET chen.title = 'Chief Technology Officer'
CREATE (reed:Person {name: 'Dr. Evelyn Reed'})
CREATE (reed)-[:REPORTS_TO]->(chen) 

Option 2: Combine CREATE and SET in a single query block
CREATE (chen:Person {name: 'Mr. David Chen'})
WITH chen
SET chen.title = 'Chief Technology Officer'
CREATE (reed:Person {name: 'Dr. Evelyn Reed'})
CREATE (reed)-[:REPORTS_TO]->(chen)


No comments:

Post a Comment