Tengo una red de nodos en la base de datos neo4j que incluye nodos multinivel algo así como,
padre -> hijo -> sub hijo -> ...y así sucesivamente
Ahora lo que necesito es escribir una consulta que me dé la respuesta en el siguiente formato.
nodes = [ { id: parent1, children : [{ id: child1, children: [ { id: sub child1, children: [... So on] }, { id: sub child2, children: [... So on] } ] }] }, { id = parent2, children : [...so on] } ]Puedes hacer algo como:
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; Hacer coincidir los principales padres, que no señala a nadie, luego usar apoc.path.expandConfig para obtener sus rutas y luego apoc.convert.toTree para obtener la estructura en forma de árbol que desea.
En una muestra de datos:
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)Vuelve:
[{ "_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 }]