@frant.hartm 的回答完全正确!但是,如果您想使用稍微不同的方法,您可以考虑以下方法:
想象下图:
create
(p1:Employee {name:"John"})-[:works_at]->(e1:Employer {name:"Microsoft"}),
(p1)-[:works_at]->(e2:Employer {name:"Oracle"}),
(p2:Employee {name:"Jim"})-[:works_at]->(e1),
(p2)-[:works_at]->(e2)
return p1, p2, e1, e2
// RESULT:
// (Jim)-works_at->(Microsoft)
// (Jim)-works_at->(Oracle)
// (John)-works_at->(Microsoft)
// (John)-works_at->(Oracle)
为了让COLLECT 获得良好的输出格式,您还可以使用 literal maps,如下例所示:
MATCH
(a:Employee)-[r:works_at]->(e:Employer)
WITH
a,
r,
COLLECT({name:e.name, id:ID(e)}) AS employers
WITH
a,
COLLECT({ type : type(r), employers : employers}) AS employerRels
WITH
{ name : a.name, id: ID(a), employers : employerRels} AS employee
RETURN
employee
然后,很棒的结果将像这样很好地格式化 JSON:
{
"name": "Jim",
"id": 227,
"employers": [
{
"type": "works_at",
"employers": [
{
"name": "Oracle",
"id": 226
}
]
},
{
"type": "works_at",
"employers": [
{
"name": "Microsoft",
"id": 225
}
]
}
]
},
{
"name": "John",
"id": 224,
"employers": [
{
"type": "works_at",
"employers": [
{
"name": "Oracle",
"id": 226
}
]
},
{
"type": "works_at",
"employers": [
{
"name": "Microsoft",
"id": 225
}
]
}
]
}