当前位置:  开发笔记 > 前端 > 正文

使用Cypher从树中返回嵌套的分层JSON

如何解决《使用Cypher从树中返回嵌套的分层JSON》经验,为你挑选了1个好方法。

我目前正在使用console.neo4j.org上的示例数据编写一个输出分层JSON的查询.

使用创建示例数据

create (Neo:Crew {name:'Neo'}), (Morpheus:Crew {name: 'Morpheus'}), (Trinity:Crew {name: 'Trinity'}), (Cypher:Crew:Matrix {name: 'Cypher'}), (Smith:Matrix {name: 'Agent Smith'}), (Architect:Matrix {name:'The Architect'}),
(Neo)-[:KNOWS]->(Morpheus), (Neo)-[:LOVES]->(Trinity), (Morpheus)-[:KNOWS]->(Trinity),
(Morpheus)-[:KNOWS]->(Cypher), (Cypher)-[:KNOWS]->(Smith), (Smith)-[:CODED_BY]->(Architect)

理想的输出如下

name:"Neo"
children: [
  { 
    name: "Morpheus",
    children: [
      {name: "Trinity", children: []}
      {name: "Cypher", children: [
        {name: "Agent Smith", children: []}
      ]}
    ]
  }
]
}

现在,我正在使用以下查询

MATCH p =(:Crew { name: "Neo" })-[q:KNOWS*0..]-m
RETURN extract(n IN nodes(p)| n)

得到这个

[(0:Crew {name:"Neo"})]
[(0:Crew {name:"Neo"}), (1:Crew {name:"Morpheus"})]
[(0:Crew {name:"Neo"}), (1:Crew {name:"Morpheus"}), (2:Crew {name:"Trinity"})]
[(0:Crew {name:"Neo"}), (1:Crew {name:"Morpheus"}), (3:Crew:Matrix {name:"Cypher"})]
[(0:Crew {name:"Neo"}), (1:Crew {name:"Morpheus"}), (3:Crew:Matrix {name:"Cypher"}), (4:Matrix {name:"Agent Smith"})]

有任何提示来解决这个问题吗?谢谢



1> cybersam..:

在neo4j 3.x中,在neo4j服务器上安装APOC插件后,可以调用该apoc.convert.toTree过程来生成类似的结果.

例如:

MATCH p=(n:Crew {name:'Neo'})-[:KNOWS*]->(m)
WITH COLLECT(p) AS ps
CALL apoc.convert.toTree(ps) yield value
RETURN value;

...将返回如下所示的结果行:

    {
      "_id": 127,
      "_type": "Crew",
      "name": "Neo",
      "knows": [
        {
          "_id": 128,
          "_type": "Crew",
          "name": "Morpheus",
          "knows": [
            {
              "_id": 129,
              "_type": "Crew",
              "name": "Trinity"
            },
            {
              "_id": 130,
              "_type": "Crew:Matrix",
              "name": "Cypher",
              "knows": [
                {
                  "_id": 131,
                  "_type": "Matrix",
                  "name": "Agent Smith"
                }
              ]
            }
          ]
        }
      ]
    }

推荐阅读
echo7111436
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有