Set relationship direction by variable injected into Cypher query

Viewed 22

I'm developing a graph model in Neo4j where the direction of a relation has a meaning. When creating new nodes and the relation between them, I would like to dynamically set the relation's direction with a variable injected into the Cypher query.

In other words, I would like to do either

CREATE (from:Signature)-[:CONNECTS]->(to:Signature)

or

CREATE (from:Signature)<-[:CONNECTS]-(to:Signature)

with only one query, controlling the direction with a variable. (Example heavily simplified.)

For reference, I am using TypeScript and the neo4j-driver package to interact with a Neo4j database. As I'm only just beginning my journey to graph databases, I am currently simply writing raw queries instead of using a query builder or an OGM (although my understanding is that a proper OGM for Neo4j does not even exist in the NPM ecosystem). Thus the motivation behind this question is to avoid duplicating a complex query just to be able to flip the relation's direction. (Clearly, this would be trivial even with just a query builder.)

1 Answers

This could be an approach, using direction AS a variable

  WITH n,m,
       'out' AS direction
       
  WITH CASE WHEN direction = 'out' THEN n ELSE m END AS from,
       CASE WHEN direction = 'out' THEN m ELSE n END AS to
  
  CREATE (from)-[:CONNECTS]->(to)
Related