Search code examples
neo4jcypherneo4jclient

How to remove relations while iteration with UNWIND using cypher


The following query getting all groups of specific user then unwind on each result(each group) and should remove all incoming relations only if count relations to that group is 1.

example: group1<-user1  (will delete the incoming relationship to the group)

         group1-<user1 
         group1-<user2 (will remain all incoming relationships to the group)

can assist complete it?

MATCH (me:userId{{1})-[rel:relation_group]-(allGroups:GROUP)
unwind userGroups as group  
 //how to use CASE or WHERE in order to check if this group 
has only 1 relationship just remove it 

Thanks.


Solution

  • You can use size in WHERE, example :

    MATCH (me:userId{{1})-[rel:relation_group]-(allGroups:GROUP)
    WHERE size((allGroups)<-[:relation_group]-()) = 1
    DELETE rel
    

    You don't need to iterate, by default the subsequent clauses after a MATCH will be executed for each row found in the MATCH, so let's say the first MATCH returns the following :

    me     rel     allGroups
    1      rel3     node5
    1      rel4     node6
    

    Then the DELETE will be executed for the first row, then for the second row, etc...