user1872862
user1872862

Reputation: 79

Neo4j : Get top level node along with their child

I have total 10 nodes in my database

M1 -> M2 -> M4 -> M5
M1 -> M3 
M6
M7 -> M8 
M7 -> M9
M7 -> M10

I need to fire a query which should return me result like following JSON which can be used as it is to show Tree Structure in client application (without any additional processing) (Total root level records 3 but all child nodes nested depending on relation).

 [
  {
    "name": "M1",
    "child": [
      {
        "name": "M2",
        "child": [
          {
            "name": "M4",
            "child": [
              {
                "name": "M5"
              }
            ]
          }
        ]
      },
      {
        "name": "M3"
      }
    ]
  },
  {
    "name": "M6"
  },
  {
    "name": "M7",
    "child": [
      {
        "name": "M8",
      },
      {
        "name": "M9"
      },
      {
        "name": "M10"
      }
    ]
  }
]

Is something similar possible with Neo4J ( When invoked such query from Java code it should get the nested collection of nodes )

Upvotes: 1

Views: 455

Answers (1)

stdob--
stdob--

Reputation: 29172

You can use the apoc.convert.toTree from APOC. For example, in the following initial data:

MERGE (M1:TREE {name:'m1'}) MERGE (M2:TREE {name:'m2'})
MERGE (M3:TREE {name:'m3'}) MERGE (M4:TREE {name:'m4'})
MERGE (M5:TREE {name:'m5'}) MERGE (M6:TREE {name:'m6'})
MERGE (M7:TREE {name:'m7'}) MERGE (M8:TREE {name:'m8'})
MERGE (M9:TREE {name:'m9'}) MERGE (M10:TREE {name:'m10'})
MERGE (M1)-[:hasChild]->(M2) MERGE (M2)-[:hasChild]->(M4)
MERGE (M4)-[:hasChild]->(M5) MERGE (M1)-[:hasChild]->(M3)
MERGE (M7)-[:hasChild]->(M8) MERGE (M7)-[:hasChild]->(M9)
MERGE (M7)-[:hasChild]->(M10)

Query can be as follows:

// Get leaf
MATCH (T:TREE) WHERE NOT (T)-[:hasChild]->(:TREE) WITH T
// Get branches
OPTIONAL MATCH path = (P:TREE)-[:hasChild*0..]->(T) WHERE NOT (P)<-[:hasChild]-()
WITH collect(path) as paths
// Convert paths to tree
CALL apoc.convert.toTree(paths) YIELD value
RETURN value as tree

Upvotes: 1

Related Questions