I am using Spring Data Neo4J to define a undirected relationship between different persons. A sample entity class has been provided below.
@NodeEntity(label="Person")
public class Person {
@GraphId
private Long id;
private String name;
@Relationship(type = "FRIEND_WITH", direction=Relationship.UNDIRECTED)
List<Person> friends;
}
As above, a Person has a list of friends of type "Person". The relationship is kept undirected to ensure that if a person A is "Friend_With" person B, then person B is also "Friend_With" Person A.
The code to add a friend is provided below
if((person.getFriends() == null)||(person.getFriends().size()==0)){
List<Person> friendList = new ArrayList<Person>();
friendList.add(friend);
person.setFriends(friendList);
}else{
person.getFriends().add(friend);
}
personRepository.save(person);
I have added PersonB as a friend of PersonA,so ideally, this should mean
PersonA - [:FRIEND_WITH] -> PersonB
PersonB - [:FRIEND_WITH] -> PersonA
as the relationship is undirected
But when I am querying, in Neo4J with
MATCH (p:Person)-[r:FRIEND_WITH]->(b:Person) where p.name = "PersonA" return p,b
I am getting the result as PersonA, PersonB. But when I am querying
MATCH (p:Person)-[r:FRIEND_WITH]->(b:Person) where p.name = "PersonB"
no rows are returned. Thus the direction specified in the entity class does not seem to work. Also the Graph in Neo4J browser shows a directed edge from PersonA to PersonB.
All I want is that if PersonA is a friend of PersonB, the I will get the results, no matter, which way I ask. The code seems to work for
MATCH (p:Person)-[r:FRIEND_WITH]-(b:Person) where p.name = "PersonB"
where the "->" is replaced by "-", but I do not want to use this.
What should I do ?
I am using spring-data-neo4j.version 4.0.0.RELEASE and spring-boot version spring-boot-starter-parent 1.3.0.M5
In Neo4j, ALL relationships are directed.
However, you can have the notion of undirected edges at query time. Just remove the direction from your MATCH query :
MATCH (p:Person)-[r:FRIEND_WITH]-(b:Person) where p.name = "PersonB"
Why don't you want to use this ?