如何使用 spring 数据 neo4j 查找二级朋友之间的关系
how to find the relationship between 2nd degree friends with spring data neo4j
my relationship graph as below pic
使用MATCH (n:Person {name:'1'})-[]-()-[r]-(m) RETURN m,r
会return“4”和“5”,但无法得到“4”和“5”之间的关系,实际上,“4”跟随"5","r"只代表4(4-->2)和5(5-->3)的朋友。
在 spring 数据 neo4j
domain.java
@NodeEntity(label = "Person")
public class PersonTest {
@Id
private Long id;
@Property(name = "name")
private String name;
@Relationship(type = "Follow") //direction=Relationship.DIRECTION
private List<PersonTest> friends;
Repository.java
public interface PersonRepository extends Neo4jRepository<PersonTest,Long> {
@Query("MATCH (n:Person {name:{name}})-[]-()-[r]-(m) RETURN m,r")
Collection<PersonTest> graph(@Param("name") String name);
}
Service.java
Collection<PersonTest> persons = personRepository.graph(name);
Iterator<PersonTest> result = persons.iterator();
while (result.hasNext()) {
for (PersonTest friend : p.getFriends()) {
//........here will get 2 and 3!
}
}
如何解决这个问题?得到“4”和“5”之间的关系。
要查找某个级别的相关子项,可以使用可变长度的双面模式:
MATCH (n:Person {name:'1'})-[:Follow*2]->(m)-[r:Follow]-()<-[:Follow*2]-(n)
RETURN m,r
http://console.neo4j.org/r/el2x80
更新。我认为这是一个更正确的查询:
MATCH (n:Person {name:'1'})-[:Follow*2]->(m:Person)-[r:Follow]-(k:Person)
WHERE (n)-[:Follow*2]->(k)
RETURN m, r
my relationship graph as below pic
使用MATCH (n:Person {name:'1'})-[]-()-[r]-(m) RETURN m,r
会return“4”和“5”,但无法得到“4”和“5”之间的关系,实际上,“4”跟随"5","r"只代表4(4-->2)和5(5-->3)的朋友。
在 spring 数据 neo4j
domain.java
@NodeEntity(label = "Person")
public class PersonTest {
@Id
private Long id;
@Property(name = "name")
private String name;
@Relationship(type = "Follow") //direction=Relationship.DIRECTION
private List<PersonTest> friends;
Repository.java
public interface PersonRepository extends Neo4jRepository<PersonTest,Long> {
@Query("MATCH (n:Person {name:{name}})-[]-()-[r]-(m) RETURN m,r")
Collection<PersonTest> graph(@Param("name") String name);
}
Service.java
Collection<PersonTest> persons = personRepository.graph(name);
Iterator<PersonTest> result = persons.iterator();
while (result.hasNext()) {
for (PersonTest friend : p.getFriends()) {
//........here will get 2 and 3!
}
}
如何解决这个问题?得到“4”和“5”之间的关系。
要查找某个级别的相关子项,可以使用可变长度的双面模式:
MATCH (n:Person {name:'1'})-[:Follow*2]->(m)-[r:Follow]-()<-[:Follow*2]-(n)
RETURN m,r
http://console.neo4j.org/r/el2x80
更新。我认为这是一个更正确的查询:
MATCH (n:Person {name:'1'})-[:Follow*2]->(m:Person)-[r:Follow]-(k:Person)
WHERE (n)-[:Follow*2]->(k)
RETURN m, r