cancel
Showing results for 
Search instead for 
Did you mean: 

Two results from the same node into a single query

mirkos93
Node

Hi everyone,
it's my first post in this community and I hope to do everything correctly, if not, be patient!

I'm trying to structure a small social network, but I can't develop a query that will surely be very simple for you.

The query I have to develop is the one useful for picking up posts on the wall.
I should therefore take both the posts of the users followed by the user who views the wall, and directly the posts created by the user who views the wall.
I show you a cypher query that I have developed:

MATCH (cu:User)-[:FOLLOWS]->(u:User)-[:POSTS]->(p:Post)
WHERE id(cu) = 12345 //cu stands for Current User
RETURN p

In this query cu is the user viewing the wall, u are the users followed by cu and p are the posts I would like to return.

Looking at the objectives described above, it is evident that this query cannot also return the posts created by cu. So what's the best way, in your opinion, to return both posts in a single query?
I tried also to use the EXISTS function but with very poor performance results.

1 ACCEPTED SOLUTION

mirkos93
Node

I think that i've found a solution!

MATCH (cu:User)-[:FOLLOWS*0..1]->(u:User)-[:POSTS]->(p:Post)
WHERE id(cu) = 12345 //cu stands for Current User
RETURN p

View solution in original post

2 REPLIES 2

mirkos93
Node

I think that i've found a solution!

MATCH (cu:User)-[:FOLLOWS*0..1]->(u:User)-[:POSTS]->(p:Post)
WHERE id(cu) = 12345 //cu stands for Current User
RETURN p

Cobra
Ninja
Ninja

Hello @mirkos93 and welcome to the Neo4j community

There are many ways to get what you want, but a simple one is to use the UNION clause in your case. This query will return posts from the user and its followers.

MATCH (cu:User)-[:POSTS]->(p:Post) 
WHERE id(cu) = 12345 
RETURN p 
UNION 
MATCH (cu:User)-[:FOLLOWS]->(u:User)-[:POSTS]->(p:Post) 
WHERE id(cu) = 12345
RETURN p

Regards,
Cobra