Question

I have a query like this:

MATCH (a)-[:Shout]->(b)
WHERE a.user_id=1
WITH b.post_id as b_post_id, a, b.post as b_post
MATCH (a)-[:Friend]->(c)-[:Shout]->(d)
WITH d.post_id as d_post_id, b_post_id, d.post as d_post, b_post
order by d_post_id desc, b_post_id desc
RETURN collect(distinct d_post) + collect(distinct b_post) as p

I want to return all posts that are from user and friend so I combine the 2 match the first match (a)-[:Shout]->(b) will return posts from user and the second match (a)-[:Friend]->(c)-[:Shout]->(d) will return posts from friend.

The posts of (a)-[:Shout]->(b) are

post_id: 5, post: nana
post_id: 2, post: hi

The posts of (a)-[:Friend]->(c)-[:Shout]->(d) are

post_id: 6, post: lala
post_id: 4, post: hello
post_id: 3, post: hanson

So, when I RETURN collect(distinct d_post) + collect(distinct b_post) as p, it will be P: nana, hi, lala, hello, hanson

It should be: lala, nana, hello, hanson, hi or 6,5,4,3,2

Please help me. Thanks.

Was it helpful?

Solution

How about something like

MATCH (a {user_id:1})-[:Friend*0..1]->()-[:Shout]->(b)
WITH b.post_id as post_id, b.post as post ORDER BY post_id desc
RETURN collect(post) as posts

Edit

Per comment, if you want to return the id of the node that -[:Shout]->(b) you can add an identifier for the optional friend place

MATCH (a {user_id:1})-[:Friend*0..1]->(friendOrUser)-[:Shout]->(b)
WITH friendOrUser, b ORDER BY b.post_id desc
RETURN friendOrUser.user_id, b.post

Here friendOrUser binds both the user a and his friends.

OTHER TIPS

Try below. The query is not very clean but will do the job.

MATCH (a)-[:Shout]->(b)
WHERE a.user_id=1
WITH b,a
MATCH (a)-[:Friend]->(c)-[:Shout]->(d)
WITH b,d
MATCH (dummy) WHERE (dummy = b OR dummy = d) 
WITH dummy ORDER BY dummy.post_id DESC
RETURN collect(distinct dummy.post) AS p
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top