0
votes

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 .

to further 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 .

1

1 Answers

0
votes

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.

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. If there are N u1/p1 results and M u2/p2 results, then you'd get N*M result rows.

To get a result with N rows (with one row per u1/p2 result), you can use something like this query:

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.