Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Neo4j Bidirectional Relationship

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 :)

like image 970
sgp Avatar asked Jun 03 '14 08:06

sgp


People also ask

Is Neo4j bidirectional?

Neo4j cannot store bidirectional relationships. No way around this, you can however treat relationships as bidirectional when querying your graph.

Can a relationship between any nodes be bidirectional in graph database?

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.

What is the bidirectional relationship?

A bidirectional relationship has both an owning side and an inverse side. A unidirectional relationship has only an owning side. The owning side of a relationship determines how the Persistence runtime makes updates to the relationship in the database.

How many directions can a relationship have in Neo4j?

Relationships always has a direction (one direction).


2 Answers

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.

like image 175
David Simons Avatar answered Sep 22 '22 18:09

David Simons


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.

like image 22
Kache Avatar answered Sep 20 '22 18:09

Kache