Search code examples
neo4jcypher

neo4j cypher: return invert relationship


We are using neo4j v4.

I have USER, COMPUTER, COMPANY nodes(IBM, HP, DELL etc),

When company is IBM, I want to reverse the edge before returning.

I tried apoc.refactor.invert() like below:

MATCH (u:USER {id: 101})
RETURN  
CASE u.preference 
WHEN 'HP'    THEN  [(n:computer)-[r: MANUFACTURED_BY]->(c:HP) | r]
WHEN 'IBM'   THEN [(n:computer)-[r:ASSEMBELED_BY]->(c:IBM) | apoc.refactor.invert(r)] 
WHEN 'DELL'   THEN [(n:computer)-[r:ASSEMBELED_BY]->(c:DELL) | r] 
WHEN 'HP_IBM' THEN xxxxxxx END
AS result;

But, getting this error: Invalid input 's'

Any idea?


Solution

  • You can use apoc.create.vRelationship to return virtual ASSEMBLED_BY relationships (with reversed directionality) for IBM users. This does not change any relationships in the DB.

    MATCH (u:USER {id: 101})
    RETURN CASE u.preference 
      WHEN 'HP'     THEN [(n:computer)-[r: MANUFACTURED_BY]->(c:HP) | r]
      WHEN 'IBM'    THEN [(n:computer)-[r:ASSEMBLED_BY]->(c:IBM) | apoc.create.vRelationship(c, 'ASSEMBLED_BY', PROPERTIES(r), n)] 
      WHEN 'DELL'   THEN [(n:computer)-[r:ASSEMBLED_BY]->(c:DELL) | r] 
      WHEN 'HP_IBM' THEN [(n:computer)-[r:ASSEMBLED_BY]->(c:HP_IBM) | r] END
    AS result;
    

    Note that the above query uses the correctly-spelled ASSEMBLED_BY relationship type.