gpt4 book ai didi

Neo4j 返回嵌套的 JSON

转载 作者:行者123 更新时间:2023-12-04 18:01:58 25 4
gpt4 key购买 nike

我的 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 并没有像我想要的那样嵌套。

是否有一个查询可以帮助我实现这一目标,或者我应该用其他编程语言进行嵌套?

最佳答案

正如评论中所说,您可以使用 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 .

关于Neo4j 返回嵌套的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44923357/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com