Pawan
Pawan

Reputation: 3

Is there a match query which will export the data as an hierarchical tree

I have the data structured in the following format:

Node Type 1 (NT1) -> Relation Type 1 (RT1) -> Node Type 2 (NT2) -> Relation Type 2 (RT2) -> Node Type 3 (NT3)

Sample Node Data in format (type, id)

NT1, A_1
NT2, B_1
NT2, B_2
NT2, B_3
NT3, C_1
NT3, C_2
NT3, C_3

Sample Relationship Data in format (type, node id1, node id2)

RT1, A_1, B_1
RT1, A_1, B_2
RT1, A_1, B_3
RT2, B_1, C_1
RT2, B_1, C_2
RT2, B_3, C_3

What I want to export is a JSON format tree with the child nodes placed under the parent node, such that the nodes are embedded/joined in the output, so:

[
  { id: A_1
     RT1: [ {
              id: B_1
              RT2: [ {id: C1 }, {id: C2} ]
            },
            {
              id: B_2 RT2: [ ]
            },
            {
              id: B_3
              RT2: [ {id: C3 } ]
            }
          ]
  }  
]

Not looking for the output to be exactly like this but basically the consumer of the data can parse the hierarchy and get the child (level 1, level 2) and beyond nodes without having to do any joins themselves.

In general, I have cycles in the graph as in C_1 connects back to A_1 and B_1, but to get it working, I simplified it. Any suggestions how it would work in the general case where only certain relationship types are traversed would be appreciated.

Thanks in advance.

I tried the BFS, DFS I think I need something similar to BFS and also tried some of the examples on StackOverflow, they give me the expanded list of the relevant nodes but it does not have the hierarchy, so the user still hast to do the joins.

Upvotes: 0

Views: 43

Answers (1)

MPesi
MPesi

Reputation: 357

Since you have a tree structure of the graph, you could try playing around with the size of the relationships of the path matched in order to get the hierarchical output of the results. You can also specify the relationships you want your graph to traverse through. Maybe a query similar to this one would be what you're looking for:

MATCH path = (n:NT1)-[:RT1 |:RT2 *]->(m)
WITH n, m, relationships(path) AS rels, size(relationships(path)) AS depth
ORDER BY depth
WITH n, COLLECT({id: m.id, RT: type(last(rels))}) AS children
RETURN {id: n.id, RT1: children} AS result 

Upvotes: 0

Related Questions