为了得到嵌套的JSON结构,我试图找出密码查询。下面我给出一个图表的例子。
MATCH (user:User {name:"User_1"})
OPTIONAL MATCH (user)-[rel*]->(subUser:User)
RETURN *
上面的查询允许我获得将所有内容转换为JSON结构所需的所有节点和关系,但这要求我在查询数据库的结果后处理所有内容。为了实现这一点,我需要匹配节点的标识和关系,以获得嵌套的JSON。我想知道是否有可能通过构建密码查询直接实现这一点。重要的是,我们不知道有多少级别的“子”用户是从User_1开始的。
预期的JSON结构:
{
"user": "User_1",
"children": [
{
"user": "User_2",
"children": [
{
"user": "User_5",
"children": []
}
]
},{
"user": "User_3",
"children": [
{
"user": "User_6",
"children": []
}
]
},{
"user": "User_4",
"children": []
}
]
}
有可能吗?
发布于 2022-10-11 05:59:41
正如@nimrod注释中所建议的那样,您可以使用apoc.convert.toTree
方法,它将给您提供树结构的JSON,如所需,但有一个警告,JSON的键将是不同的。关于数据:
MERGE (u1:User{name: 'User1'})
MERGE (u2:User{name: 'User2'})
MERGE (u3:User{name: 'User3'})
MERGE (u4:User{name: 'User4'})
MERGE (u5:User{name: 'User5'})
MERGE (u6:User{name: 'User6'})
MERGE (u1)-[:POINTS]->(u2)-[:POINTS]->(u5)
MERGE (u1)-[:POINTS]->(u3)-[:POINTS]->(u6)
MERGE (u1)-[:POINTS]->(u4)
查询:
MATCH (user:User {name:"User1"})
OPTIONAL MATCH path = (user)-[:POINTS*]->(subUser:User)
WITH collect(path) AS paths
CALL apoc.convert.toTree(paths, true, {nodes: {User: ['name']}})
YIELD value
RETURN value
产生的输出:
{
"_type": "User",
"name": "User1",
"_id": 4,
"points": [
{
"_type": "User",
"name": "User3",
"_id": 6,
"points": [
{
"_type": "User",
"name": "User6",
"_id": 9
}
]
},
{
"_type": "User",
"name": "User2",
"_id": 5,
"points": [
{
"_type": "User",
"name": "User5",
"_id": 8
}
]
},
{
"_type": "User",
"name": "User4",
"_id": 7
}
]
}
如您所见,relationship type
POINTS
代替了children
,而键name
用于用户名。其他字段_type
和_id
可以忽略。
https://stackoverflow.com/questions/74021254
复制相似问题