我有一个嵌套的has_many关系,我试图将其映射到json结果。
博客中的以下示例显示了我想要做的事情,除了它没有嵌套
MATCH (a:Person { name: "Andres" })-[:FATHER_OF]->(child)
RETURN
{name:a.name, kids:collect(child.name)} as document
我想要的是这样的东西
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
在这种情况下,我想返回一个像这样结构的json对象:
{
"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"]
}
]
}
]
}
答案 0 :(得分:4)
你可以尝试:
如果你保持匹配到章节,你将需要明确
collect(distinct book.title)
否则不会。
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
哦,如果你想在结果中包含章节,那么只需添加另一个:)
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