Reputation: 311
I have a nested has_many relationship that I'm trying to map to a json result.
The following example from the blog shows the kind of thing I want to do, except it's not nested
MATCH (a:Person { name: "Andres" })-[:FATHER_OF]->(child)
RETURN
{name:a.name, kids:collect(child.name)} as document
What I want instead is 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 a structure like this:
{
"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"]
}
]
}
]
}
Upvotes: 3
Views: 1460
Reputation: 41706
Can you try:
if you keep the match to the chapter you will need distinct
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 the chapters in the results too, then just add another with :)
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
Upvotes: 6