Aran Mulholland
Aran Mulholland

Reputation: 23935

Neo4j Cypher query RETURN distinct set of nodes

I have a simple social network graph db model. Users can follow other users and post posts. I am trying to get a list of all posts that a user has posted along with any that anyone the user follows has posted

START a=node:node_auto_index(UserIdentifier = "USER0") 
MATCH (a)-[:POSTED]->(b), (a)-[:FOLLOWS]->(c)-[:POSTED]->(d) 
RETURN b, d;

It is returning the cross product of the two, a tuple of all the values in b joined with all the values in d. (b x d) I would like just a straight list of posts. How do I do this? Do I need to do two separate queries?

Upvotes: 4

Views: 3032

Answers (2)

Aseem Kishore
Aseem Kishore

Reputation: 10858

Another way you can do it now (and IMHO the cleaner way) is to take advantage of variable length relationships.

START user=node...
MATCH (user) -[:FOLLOWS*0..1]-> (following) -[:POSTED]-> (post)
RETURN post

The advantage to this way is it lets you aggregate both your own queries and your friends/followings' queries uniformly. E.g. sorting, limiting, paginating, etc.

Upvotes: 1

Peter Neubauer
Peter Neubauer

Reputation: 6331

Anwsered at https://groups.google.com/forum/?fromgroups=#!topic/neo4j/SdM7bKNRDEA :

START a=node:node_auto_index(UserIdentifier = "USER0") 
MATCH (a)-[:POSTED]->(b)
WITH a, collect(b) as posts
MATCH (a)-[:FOLLOWS]->(c)-[:POSTED]->(d) 
RETURN posts, collect(d) as followersPosts;

Upvotes: 1

Related Questions