mathpaquette
mathpaquette

Reputation: 436

Node4j retrieve nodes grouped by least specific group

I’m new to Neo4j and I need to prototype something for yesterday. I’m still considering using a conventional relational database for doing this unless you can clearly demonstrate how convenient it is using a graph db for this specific application.

Suppose I have this chart:
Graph example

B has parent A
C has parent A
D has parent A
E has parent B
F has parent C
G has parent C
H has parent C
I has parent D

I need to retrieve the current node + 1 level grouped by the largest group of nodes as possible.

My result for node A:
A result

My result for Group 1:
Group 1 result

And so on...

I'm starting from scratch so all your suggestions will be appreciated.

Upvotes: 1

Views: 120

Answers (1)

FrobberOfBits
FrobberOfBits

Reputation: 18002

To model this hierarchy, you need a defined relation type that allows us to pick out what are the children of what. So let's assume a setup like this:

CREATE (a:Node { name: 'a' }), (b:Node { name: 'b' }), 
       (c:Node { name: 'c' }), (d:Node { name: 'd' }),
       (e:Node { name: 'e' }), (f:Node { name: 'f' }), 
       (g:Node { name: 'g' }), (h:Node { name: 'h' }),
       (i:Node { name: 'i' }),
       (a)-[:child]->(b), (a)-[:child]->(c);
/* And so on for all relationships */

Querying for a group is a very straightforward process of just traversing :child links, like this:

MATCH (a:Node { name: 'a' })-[:child*]->(groupMember:Node)
RETURN groupMember;

The magic here is just the * which allows you to match any number of relationship hops. As long as your graph has no cycles, this will always give you the complete set of descendant nodes in a hierarchy.

You can get pretty fancy from there -- limit the path length to only fetch n levels of hierarchy, impose extra conditions on what the children can be, or match this to a path and return the path through the graph rather than the nodes themselves, whatever you like.

Upvotes: 1

Related Questions