37

Is there a way to create bidirectional relationship in Neo4j using Cypher? I would like the relationship to be bidirectional rather than making two unidirectional relationships in both directions For eg:

(A)<-[FRIEND]->(B)

Rather than:

(A)-[FRIEND]->(B)
(A)<-[FRIEND]-(B)

Thanks in advance :)

sgp
  • 1,738
  • 6
  • 17
  • 31

2 Answers2

48

No, there isn't. All relationships in neo4j have a direction, starting and ending at a given node.

There are a small number of workarounds.

  • Firstly, as you've suggested, we can either have two relationships, one going from A to B and the other from B to A.

  • Alternatively, when writing our MATCH query, we can specify to match patterns directionlessly, by using a query such as

    MATCH (A)-[FRIEND]-(B) RETURN A, B
    

    which will not care about whether A is friends with B or vice versa, and allows us to choose a direction arbitrarily when we create the relationship.

David Simons
  • 634
  • 8
  • 10
  • 1
    Do you mind expounding a little on the pros and cons of alternatives the alternatives. Which one is better and why? – qualebs Sep 20 '14 at 11:54
  • Is this what you'd do when you're actually creating the relationship, too? Or do you pick an arbitrary direction then – Craig Brett May 28 '15 at 15:35
  • @CraigBrett Cypher doesn't allow you to `CREATE` a relationship without a direction. That makes sense, since it would be wrong to randomly decide a direction without you specifying one. – ADTC May 14 '16 at 19:30
  • @qualebs From a Facebook perspective, the second one would be better because you only have one relationship, not two, reducing your chances of errors and other anomalies. And you can store two kinds of data in that one relationship: (1) who is a friend of who (when you ignore the direction) (2) who sent the friend request (source node) and who accepted it (target node). – ADTC May 14 '16 at 19:32
  • What if the relationship is actually directional, i.e. A negatively regulates B and B is positively regulated by C but the relationship goes from C to B, how can I return in same query: Row 1: A - B and Row 2: C + B. The relation itself it directional not just the edge – Brian Wiley Oct 24 '20 at 14:02
24

According to this article: Modeling Data in Neo4j: Bidirectional Relationships

The strictly better choice is to create a relationship in an arbitrary direction and not specify the direction when querying:

MATCH (neo)-[:PARTNER]-(partner)

The engine is capable of traversing the edge in either direction. Creating the anti-directional edge is unnecessary and only serves to waste space and traversal time.

Kache
  • 15,647
  • 12
  • 51
  • 79
  • Please note that this only works for relationship types which either are bidirectional or don't exist at all, such as e.g. Facebook friends. But there exist relationship types for which both unidirectional and bidirectional can exist, such as "knows". – Bastian Blankenburg Oct 29 '20 at 07:36