我的Neo4j数据库包含家谱关系。
我想以嵌套的JSON格式提取数据,如下所示:
{
"firstname":"Jon",
"lastname":"Smith",
"parents":[
{
"firstname":"Anna",
"lastname":"Smith",
"parents":[
{
"furstname":"Peter",
"lastname":"Doe",
"parents":[
{
"firstname":"Jessica",
"lastname":"Doe"
},
{
"firstname":"Clayton",
"lastname":"Doe"
}
]
},
{
"firstname":"Nell",
"lastname":"Gordon",
"parents":[
{
"firstname":"Jessica",
"lastname":"Roberts"
},
{
"firstname":"Randy",
"lastname":"Roberts"
}
]
}
]
}
]
}
以便将其可视化。
我尝试了以下查询:
MATCH path = (p:Person)-[r:PARENT_OF*1..3]-(k:Person)
WHERE k.id = '1887'
UNWIND r as rel
RETURN StartNode(rel).firstname, rels(path), EndNode(rel).firstname
使用py2neo库如下:
dumps(graph.run(query).data())
但是JSON并没有像我想要的那样嵌套。
是否有一个查询可以帮助我实现这个目标,或者我应该用其他编程语言进行嵌套?
答案 0 :(得分:6)
如评论中所述,您可以使用APOC Procedure apoc.convert.toTree
。看:
1 - 根据您的问题创建样本数据集:
CREATE (jonsmith:Person {firstname:"Jon", lastname:"Smith"})
CREATE (annasmith:Person {firstname:"Anna", lastname:"Smith"})
CREATE (peterdoe:Person {firstname:"Peter", lastname:"Doe"})
CREATE (jessicadoe:Person {firstname:"Jessica", lastname:"Doe"})
CREATE (claytondoe:Person {firstname:"Clayton", lastname:"Doe"})
CREATE (nellgordon:Person {firstname:"Nell", lastname:"Gordon"})
CREATE (jessicaroberts:Person {firstname:"Jessica", lastname:"Roberts"})
CREATE (randyroberts:Person {firstname:"Randy", lastname:"Roberts"})
CREATE (jonsmith)-[:PARENT_OF]->(annasmith)
CREATE (annasmith)-[:PARENT_OF]->(peterdoe)
CREATE (annasmith)-[:PARENT_OF]->(nellgordon)
CREATE (peterdoe)-[:PARENT_OF]->(jessicadoe)
CREATE (peterdoe)-[:PARENT_OF]->(claytondoe)
CREATE (nellgordon)-[:PARENT_OF]->(jessicaroberts)
CREATE (nellgordon)-[:PARENT_OF]->(randyroberts)
2 - 运行查询:
MATCH path = (jon:Person {firstname:'Jon', lastname:'Smith'})-[:PARENT_OF*]-(:Person)
WITH collect(path) as paths
CALL apoc.convert.toTree(paths) yield value
RETURN value;
3 - 结果:
{
"_type": "Person",
"_id": 9,
"firstname": "Jon",
"lastname": "Smith",
"parent_of": [
{
"_id": 10,
"_type": "Person",
"firstname": "Anna",
"lastname": "Smith",
"parent_of": [
{
"_id": 11,
"_type": "Person",
"firstname": "Peter",
"lastname": "Doe",
"parent_of": [
{
"_id": 12,
"_type": "Person",
"firstname": "Jessica",
"lastname": "Doe"
},
{
"_id": 13,
"_type": "Person",
"firstname": "Clayton",
"lastname": "Doe"
}
]
},
{
"_id": 14,
"_type": "Person",
"firstname": "Nell",
"lastname": "Gordon",
"parent_of": [
{
"_id": 15,
"_type": "Person",
"firstname": "Jessica",
"lastname": "Roberts"
},
{
"_id": 16,
"_type": "Person",
"firstname": "Randy",
"lastname": "Roberts"
}
]
}
]
}
]
}
请记住根据您使用的Neo4j版本安装APOC程序。请查看version compatibility matrix。