Has_many nested relationships in cypher

I have a has_many nested relation that I'm trying to match with a json result.

The following blog example shows what I want to do, except for it not nested

MATCH (a:Person { name: "Andres" })-[:FATHER_OF]->(child) RETURN {name:a.name, kids:collect(child.name)} as document 

Instead, I want something like this

  MATCH (a:Person { name: "Andres" })-[:FATHER_OF]->(child)-[:has_read]->(book)-[:has_chapter]->(chapter) RETURN {name:a.name, kids:collect({"name":child.name, has_read:collect(book)})} as document 

In this case, I would like to return a json object of such a structure:

 { "name": "Andres" "kids": [ { "name":"Bob" "has_read": [ { "name":"Lord of the Rings", "chapters": ["chapter1","chapter2","chapter3"] }, { "name":"The Hobbit", "chapters": ["An unexpected party","Roast mutton"] } ] }, { "name":"George" "has_read": [ { "name":"Lord of the Rings", "chapters": ["chapter1","chapter2","chapter3"] }, { "name":"Silmarillion", "chapters": ["chapter1","chapter2"] } ] } ] } 
+1
source share
1 answer

Can you try:

if you keep matching the chapter, you will need different collect(distinct book.title) otherwise not.

 MATCH (a:Person { name: "Andres" })-[:FATHER_OF]->(child), (child)-[:has_read]->(book)-[:has_chapter]->(chapter) WITH a,child,collect(distinct book.title) as books RETURN {name:a.name, kids:collect({name:child.name, has_read:books})} as document 

Oh, and if you want to include chapters in the results as well, just add one more :)

 MATCH (a:Person { name: "Andres" })-[:FATHER_OF]->(child), (child)-[:has_read]->(book)-[:has_chapter]->(chapter) WITH a,child, {title: book.title, chapters: collect(chapter.title)} as book_doc WITH a,child, collect(book_doc) as books RETURN {name:a.name, kids:collect({name:child.name, has_read:books})} as document 

see: http://console.neo4j.org/r/kua2pi

+3
source

All Articles