简体   繁体   中英

neo4j “try” to create relationship to node

How can I write the next cyhper query without error?

Match (n: {id :"someid"}),(x {id:"otherId"})
OPTIONAL MATCH (n)-[]->(t:Other)

merge x-[]->(t)`

The problem is that there is a cance that t will be null and ill get an error: Expected to find a node at t but found nothing Some(null)

this is the complete query:

MATCH (traveler:${labels.N_TRAVELER} {id: {traveler}.id})
        OPTIONAL MATCH (traveler)-[r:${labels.R_TRAVELER_LATEST_EVENT}]->(prev:${labels.N_EVENT})
        OPTIONAL MATCH (interest:${labels.N_INTERESTS}) WHERE interest.id IN {interests}

        DELETE r
        MERGE (traveler)-[:${labels.R_TRAVELER_LATEST_EVENT}]->(trip:${labels.N_TRIP_EVENT})
        ON CREATE SET trip={trip}

        MERGE (traveler)-[:${labels.R_TRAVELER_WRITE_TRIP}]->(trip)
        MERGE (trip)-[:${labels.R_TRIP_INTEREST}]->(interest)

        WITH trip, collect(prev) as prevs
        UNWIND prevs as prev
        MERGE (trip)-[:${labels.R_EVENT_PREV_EVENT}]->(prev)
        WITH trip
        RETURN properties(trip) as trip`

all the labels. are just strings.. {interests} is an array of ids

Basically im tying to create a linked list of trips

The first solution is to use only MATCH, which will then stop the query if there are no t nodes.

MATCH (n {id:"someid"}), (x {id:"otherId"})
MATCH (n)-->(t:Other)
MERGE (x)-[:RELATIONSHIP]->(t)

The second solution in case this query portion is part of a larger query and you need to do stuff afterwards is to collect the t, in the case of null the collection will be empty and thus you can iterate only if it contains elements :

MATCH (n {id:"someid"}), (x {id:"otherId"})
OPTIONAL MATCH (n)-->(t:Other)
WITH n, x, collect(t) as ts
UNWIND ts as t
MERGE (x)-[:RELATIONSHIP]->(t)
WITH n, x
// continue query

Here is the workaround I would use to handle the optional MERGE :

MATCH (n {id:"someid"}), (x {id:"otherId"})
OPTIONAL MATCH (n)-->(t:Other)
FOREACH(y IN CASE WHEN t IS NULL THEN [] ELSE [1] END | MERGE (x)-[:RELATIONSHIP]->(t));

The FOREACH will only do the MERGE if t is not NULL .

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