[英]Java Neo4j Cypher Or Match
I have a graph were user can have a post and also can have a friend that have a post , the friend can be followed or not . 我有一个图,用户可以发帖,也可以有一个朋友发帖,该朋友可以关注也可以不关注。
how can i query all the posts by the user and the friends that he is following ? 我如何查询用户及其跟随的朋友的所有帖子?
I tried this : 我尝试了这个:
" MATCH (u1:User)-[:POSTED]->(p1:Post)"
+ " WHERE u1.username =~ '"+user+"'"
+ " OPTIONAL MATCH (u3:User)-[:FOLLOWING]->(u2:User)-[:POSTED]->(p2:Post),"
+ " (u3:User)-[:FRIEND_OF]->(u2:User)"
+ " WHERE u3.username =~ '"+user+"' return u1.username, u1.name,"
+ "p1 ,u2.username, u2.name , p2";
but this query returns duplicates, lets say we have our user and a friend . 但是此查询返回重复项,可以说我们有我们的用户和一个朋友。
the frien have one post and the user have two , the query returns the friend post twice its like for every MATCH the query returns also the result of OPTIONAL MATCH . 朋友有一个帖子而用户有两个,则查询返回朋友帖子两次,就像每个MATCH一样 ,查询还返回OPTIONAL MATCH的结果。
to further exaplain: 进一步exaplain:
(u:User)-[:POSTED]->(p:Post)
(u:User)-[:FRIEND_OF]->(u2:User)
(u:User)-[:FOLLOWING]->(u2:User)-[:POSTED]->(p2:Post)
these are the relationships that exist what i want is all Posts (:Post) that meet those relationships without duplicates and preferably with single query . 这些是存在的关系,我想要的是满足这些关系的所有帖子(:Post),这些重复不重复,最好是使用单个查询。
First of all, your query is much more complex than it needs to be. 首先,您的查询比需要的要复杂得多。 This simpler query should be equivalent. 这个更简单的查询应该是等效的。 I assume that {user}
is supplied as a parameter . 我假设{user}
作为参数提供 。
MATCH (u1:User {username: {user}})-[:POSTED]->(p1:Post)
OPTIONAL MATCH
(u1)-[:FOLLOWING]->(u2:User)-[:POSTED]->(p2:Post),
(u1)-[:FRIEND_OF]->(u2)
RETURN u1.username, u1.name, p1, u2.username, u2.name, p2;
The reason you get multiple rows with the same p2
values is because your RETURN
clause is returning values related to u1
and u2
together. 获得具有相同p2
值的多行的原因是因为RETURN
子句将一起返回与u1
和u2
相关的值。 If there are N
u1/p1 results and M
u2/p2 results, then you'd get N*M
result rows. 如果有N
u1 / p1个结果和M
u2 / p2个结果,那么您将得到N*M
结果行。
To get a result with N rows (with one row per u1/p2
result), you can use something like this query: 要获得N行的结果(每个u1/p2
结果一行),可以使用以下查询:
MATCH (u1:User {username: {user}})-[:POSTED]->(p1:Post)
OPTIONAL MATCH
(u1)-[:FOLLOWING]->(u2:User)-[:POSTED]->(p2:Post),
(u1)-[:FRIEND_OF]->(u2)
RETURN
u1.username, u1.name, p1,
COLLECT({username: u2.username, name: u2.name, p2: p2}) AS friends;
Each result row will have a friends
collection with the data for each relevant friend. 每个结果行将有一个friends
集合,其中包含每个相关好友的数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.