密码中的嵌套 has_many 关系

use*_*696 2 neo4j cypher

我有一个嵌套的 has_many 关系,我试图将其映射到 json 结果。

博客中的以下示例显示了我想做的事情,但它不是嵌套的

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

我想要的是这样的

 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
Run Code Online (Sandbox Code Playgroud)

在这种情况下,我想返回一个结构如下的 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"]
                           }
                         ]
           }

          ]
}
Run Code Online (Sandbox Code Playgroud)

Mic*_*ger 5

你能试一下吗:

如果您保持与章节的匹配,您将需要不同, 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
Run Code Online (Sandbox Code Playgroud)

哦,如果你也想在结果中包含这些章节,那么只需添加另一个:)

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
Run Code Online (Sandbox Code Playgroud)

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