Collapse a collection of nodes by `n` the number of nodes in a directed acyclic graph (DAG)

We have a graph of geographic regions and countries associated with directional relationships [:PART_OF]

:

http://console.neo4j.org/?id=ats4i9

enter image description here

Let's have a random subset of nodes from the graph, a special case would be collecting all leaf nodes (which have no descendants):

MATCH (endnode:Geography)-[:PART_OF*]->(parent:Geography)
WHERE NOT (:Geography)-[:PART_OF]->(endnode:Geography)
RETURN endnode.name
// ['Ghana','Nigeria','Iran','Russia','Germany','United States', 'Mexico', 'Brazil']

      

For n = 1,2,3,..

how to write Cypher that collapses the above collection into a collection of exactly n

nodes where each node is an ancestor or identical to one or more nodes in the original collection. Moreover, no node in the original collection can be dropped from more than one of the nodes in the collapsed collection (no overlap condition).

For example, if n=1

, the result for the above initial set should be World

node.

If n=2

, the result should be ['Americas','EMEA']

.

If n=4

, the result must be either ['North America', 'South America & Africa', 'Europe', 'Asia']

or ['Americas', 'Africa', 'Europe', 'Asia']

.

+3


source to share





All Articles