【问题标题】:Nested has_many relationships in cypher密码中的嵌套 has_many 关系
【发布时间】:2026-01-18 07:40:02
【问题描述】:

我有一个嵌套的 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"]
                           }
                         ]
           }

          ]
}

【问题讨论】:

    标签: neo4j cypher


    【解决方案1】:

    你可以试试:

    如果你保持与章节的匹配,你将需要不同的 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
    

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

    【讨论】:

    • "collect({name:child.name, has_read:books})" 我以前没有见过这种收集语法。它在任何地方都有记录吗?