Matching nodes in a nested FOREACH

Sorry about double post! Tried looking for solutions but did not find any and I am not sure how to approach this.

I have a nested FOREACH loop that needs to match a tag to multiple labels.

OPTIONAL MATCH (a: Article {URL: event.URL})

FOREACH(ignoreme in case when a is  null then [1] else [] end |
CREATE (a: Article {URL: event.URL})
//other statements ..... //
FOREACH (relation in CASE WHEN event.article.nlp_relations is not null then event.article.nlp_relations else [] end |

         match (a)-[:HAS_NLP_TAG]->(t_from) where (t_from:Tag or t_from:Entity) and t_from.value = relation.from.value
        match (a)-[:HAS_NLP_TAG]->(t_to) where (t_to:Tag or t_to:Entity) and t_to.value = relation.to.value
        call apoc.create.relationship(t_from,relation.type , {}, t_to)
)     
 ) 

This does not work because you cannot use a match inside a foreach. I can say that there will always be a node to match as it will be created earlier in the same query. so it will never be null, but I do not know how to express this in this current form. Can anybody help

could you use UNWIND instead of FOREACH to do this?

e.g. something like this:

OPTIONAL MATCH (a: Article {URL: event.URL})

 UNWIND case when a is  null then [1] else [] end AS ignoreMe
 CREATE (a: Article {URL: event.URL})
 UNWIND CASE WHEN event.article.nlp_relations is not null then event.article.nlp_relations else [] end AS relation
match (a)-[:HAS_NLP_TAG]->(t_from) where (t_from:Tag or t_from:Entity) and t_from.value = relation.from.value
match (a)-[:HAS_NLP_TAG]->(t_to) where (t_to:Tag or t_to:Entity) and t_to.value = relation.to.value
call apoc.create.relationship(t_from,relation.type , {}, t_to)

Can we use APOC call inside forEACH?

No, FOREACH can only contain writing clauses (SET, REMOVE, CREATE, DELETE, MERGE). You should use UNWIND instead.

1 Like

The documentation on this page should be updated:

because it only shows: CREATE , MERGE , DELETE , and FOREACH. Is DETACH another command that is allowed inside FOREACH ?

REMOVE and SET should be in there, I'll ask for an update here.

DETACH isn't a clause on its own, you only see it as DETACH DELETE, so it's a modifier on DELETE. Likewise for ON CREATE <SET/REMOVE> and ON MATCH <SET/REMOVE> that can follow MERGE operations.