I am having a node network in the neo4j database which includes multilevel nodes something like,
parent -> child -> sub child -> ...and so on
Now what I need is I need to write a query that will give me the response in the below format.
nodes = [
{
id: parent1,
children : [{
id: child1,
children: [
{
id: sub child1,
children: [... So on]
},
{
id: sub child2,
children: [... So on]
}
]
}]
},
{
id = parent2,
children : [...so on]
}
]
You can do something like:
MATCH (p:Person)
WHERE size((p)<--()) = 0
CALL apoc.path.expandConfig(p, {
relationshipFilter: "PARENT>"
})
YIELD path
WITH collect(path) AS paths
CALL apoc.convert.toTree(paths)
YIELD value
RETURN value;
Matching the top parents, which points no one, then using apoc.path.expandConfig to get their paths and then apoc.convert.toTree in order to get the tree-shape structure that you want.
On a sample data:
MERGE (a:Person{key: 1})
MERGE (b:Person{key: 2})
MERGE (c:Person{key: 3})
MERGE (d:Person{key: 4})
MERGE (e:Person{key: 5})
MERGE (f:Person{key: 6})
MERGE (g:Person{key: 7})
MERGE (h:Person{key: 8})
MERGE (i:Person{key: 9})
MERGE (b)-[:PARENT]-(a)
MERGE (d)-[:PARENT]-(c)
MERGE (d)-[:PARENT]-(i)
MERGE (f)-[:PARENT]-(e)
MERGE (g)-[:PARENT]-(b)
MERGE (g)-[:PARENT]-(d)
MERGE (e)-[:PARENT]-(h)
It returns:
[{
"_type": "Person",
"parent": [
{
"_type": "Person",
"parent": [
{
"_type": "Person",
"_id": 1444,
"key": 8
}
],
"_id": 1441,
"key": 5
}
],
"_id": 1442,
"key": 6
},
{
"_type": "Person",
"parent": [
{
"_type": "Person",
"parent": [
{
"_type": "Person",
"_id": 1437,
"key": 1
}
],
"_id": 1438,
"key": 2
},
{
"_type": "Person",
"parent": [
{
"_type": "Person",
"_id": 1439,
"key": 3
},
{
"_type": "Person",
"_id": 1445,
"key": 9
}
],
"_id": 1440,
"key": 4
}
],
"_id": 1443,
"key": 7
}]