密码中的嵌套 has_many 关系 [英] Nested has_many relationships in cypher

查看:17
本文介绍了密码中的嵌套 has_many 关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我想要的是这样的

 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 对象:

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

          ]
}

推荐答案

你可以试试:

如果你保持与章节的匹配,你将需要不同的collect(distinct book.title) 否则不会.

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

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

这篇关于密码中的嵌套 has_many 关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆