It is possible using, Cypher as well. I created your graph using the following Cypher query, locally:
MERGE (p:Person{name: 'Alex', department: 'HR'})
MERGE (p1:Person{name: 'John', department: 'HR'})
MERGE (p2:Person{name: 'Kate', department: 'IT'})
MERGE (p3:Person{name: 'Mike', department: 'Sales'})
MERGE (p1)-[:R]->(p3)
MERGE (p1)-[:R]->(p2)
MERGE (p2)-[:R]->(p1)
MERGE (p)-[:R]->(p2)
Now, to convert it into the desired graph, you can try the following Cypher query:
MATCH (p:Person)
WITH distinct p.department AS departmentName
MERGE (d:Department{name: departmentName}) <-- First create all the distinct department nodes
WITH COLLECT(departmentName) AS departments
UNWIND departments AS departmentName
MATCH (p:Person{department:departmentName})
OPTIONAL MATCH (p)<-[:R]-(p1:Person)
WITH departmentName, p1 WHERE p1 IS NOT NULL
WITH departmentName, p1.department AS sourceDepartment, count(distinct p1) AS relCount <-- For each department find out the number of distinct incoming relations, with respect to each department
MATCH (d1:Department{name: departmentName})
MATCH (d2:Department{name: sourceDepartment})
MERGE (d1)<-[:R{count: relCount}]-(d2) <-- Create the relationships between department and store the count in the relationship
To check the department nodes, and verify them, run this:
MATCH (n:Department) RETURN n
In the end, if required you can delete all the Person
nodes, like this:
MATCH (n:Person) DETACH DELETE n