简体   繁体   中英

Relationship Creation for other properties skipped if property is Null in Cypher query

I have a cypher query for creating nodes in batch.

Query

UNWIND {batch} as row MERGE(m:TempEncounter {encounterId: row.encounterId}) ON CREATE SET m+=row
WITH m,row MATCH (u:Users {userId:  row.creator }) MERGE (m)-[:USERS]->(u)
WITH m,row MATCH (l:Location {locationId:  row.locationId }) MERGE (m)-[:LOCATION]->(l)
WITH m,row MATCH (p:Patient {patientId:  row.patientId }) MERGE (m)-[:PATIENT]->(p)
WITH m,row MATCH (e:EncounterType {encounterTypeId:  row.encounterType }) MERGE (m)-[:ENCOUNTERTYPE]->(e)
WITH m,row MATCH (u2:Users {userId:  row.voidedBy }) MERGE (m)-[:USERS]->(u2)
return m;

The problem with above cypher query is that suppose locationId is NULL for row1 (but may not for other rows) then relationship starting from LOCATION to USERS would not be created. Although other properties may present like(voidedBy, enounterType)

How can I improve my cypher query so that it would skip making a particular relationship if not present in row but make others which are present in row.

I am using this query for increment my nodes in neo4j. Performance is required here

I don't know if this query will be more performant or not, but the way to do what you want is the following :

UNWIND {batch} as row 
  MERGE(m:TempEncounter {encounterId: row.encounterId}) 
    ON CREATE SET m+=row
  WITH m,row 
    OPTIONAL MATCH (u:Users {userId:  row.creator })
    FOREACH( node IN filter(x IN [u] WHERE x IS NOT NULL) |
      MERGE (m)-[:USERS]->(node)
    )
  WITH m, row
    OPTIONAL MATCH (l:Location {locationId:  row.locationId })
    FOREACH( node IN filter(x IN [l] WHERE x IS NOT NULL) |
      MERGE (m)-[:LOCATION]->(node)
    )
  ...

If this query is not enought performant, you should try to split this query in many parts (one for each relationship), and do the batch in my code by managing manually my transaction's commit.

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