2013-12-19 52 views
1

我有一個嵌套的has_many關係,我試圖映射到json結果。嵌套has_many關係在密碼

從博客下面的例子顯示我想要做的事情,但它不是嵌套

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"] 
          } 
         ] 
      } 

      ] 
} 

回答

3

你可以試試:

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

+0

「收集({名孩子。姓名,has_read:books})「我以前沒有看到過這個收集語法。它記錄在任何地方嗎? –

+0

@BobB - http://neo4j.com/docs/stable/query-aggregation.html#aggregation-collect – OpenDataAlex