Konza
Konza

Reputation: 2163

Fetching node with nested relationships in neo4j cypher

I need to fetch the posts from pages which user follows. The post is divided into different contents with a HAS_CONTENT relationship. So a user can follow multiple pages. Each pages can have many posts. And the Post has an array of contents. Also the Post belongs to a page. and the final output is returned as a json.

User->follows->Page

Post->Belongsto->Page

Page->HasContent->Content

I wrote the following query and it works.

Match (u:User {uuid:"0c517930-63b3-11e5-8a9d-eaf3f38b64dc"})-[f:FOLLOWS]->(p:Page) 
with p , collect (p.uuid) as pageIds  
Match(pst: Post)-[b:BELONGS_TO]-(pge:Page) where (pge.uuid in pageIds) 
with  pst , collect (pst.uuid) as postIds
Match (post: Post)-[h:HAS_CONTENT]-(c:Content) where (post.uuid in postIds) 
with post, c order by c.orderNo asc 
with {title: post.title, contents: collect(c)} as postList 
return postList;

But I think there is a better way to do this. Please help.

Upvotes: 1

Views: 419

Answers (1)

Michael Hunger
Michael Hunger

Reputation: 41676

You have a misunderstanding, you cannot aggregate and return the same item at the same time, either aggregate with collect or return the item.

Your query is too complicated it, is much easier:

Match (u:User {uuid:"0c517930-63b3-11e5-8a9d-eaf3f38b64dc"})
      -[:FOLLOWS]->(p:Page)<-[:BELONGS_TO]-(pst:Post)
      -[:HAS_CONTENT]->(c:Content)
with p, post, c 
order by c.orderNo asc 
with p, {title: post.title, contents: collect(c)} as postList 
return {page:page.title, posts: collect(postList)} as pageList;

Upvotes: 3

Related Questions