简体   繁体   中英

A neo4j cypher query with a nullable parameter used for optional creation of a relationship - is this possible?

The context (to explain the use of the word "application" in the domain model): My software manages applications for leave (to replace old-school vacation application forms on paper).

Is there a way to handle the two similar queries below in one cypher query that accepts a nullable/optional parameter "projectManager"?

//createApplicationForUserWithProjMgr:
     match (u:User), (s:User), (p:User), (l:User)
         where u.username={username}  and
         s.username={substitute} and
         p.username={projectManager} and
         l.username={lineManager}
     create (u)-[ur:APPLIED_FOR]->(a:Application),
         (a)-[sr:SUBSTITUTE]->(s),
         (a)-[pr:PROJECT_MANAGER]->(p),
         (a)-[lr:LINE_MANAGER]->(l)
   set a={application}
   return a, s, l, u, sr, lr, ur, p, pr"""

//createApplicationForUserWithoutProjMgr:
     match (u:User), (s:User), (l:User)
         where u.username={username}  and
         s.username={substitute} and
         l.username={lineManager}
     create (u)-[ur:APPLIED_FOR]->(a:Application),
         (a)-[sr:SUBSTITUTE]->(s),
         (a)-[lr:LINE_MANAGER]->(l)
     set a={application}
     return a, s, l, u, sr, lr, ur"""

This is technically possible, but the solution is a hack and you are currently better off, unless this is a performance bottleneck, to do it in two queries for clarity. I believe there will be support added to do this in a clean way later on, but it's not currently in development.

The hack is to use FOREACH as a branch statement, so foreach project manager, create one, which will create none if no project manager was sent in as a parameter. You'll need to convert the null to an empty list in that case, but you can use COALESCE for that:

FOREACH( manager IN COALESCE(managers ,[]) | CREATE (pm:ProjectManager))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM