chartsneo4jgraph-databasesneo4j-apoc

Neo4j group nodes with property


In Neo4j, I want to create a query that returns nodes grouped on common property without altering my graph. For example, if I have the following graph where each person has a property corresponding to his department in the company:

enter image description here

I want my query to return a graph like the following, where the nodes are replaced by the property and where the weight of the edges corresponds to the number of relations:

enter image description here

Do you have any idea how to proceed? I looked at APOC nodes collapse without success.


Solution

  • This is the way to return the subgraph using apoc.nodes.collapse.

    MATCH (p:Person)-[:R]->(c:Person)
    WITH c, collect(p) as subgraph 
    CALL apoc.nodes.collapse(subgraph,{properties:'combine', countMerge:false}) 
    YIELD from, rel, to WHERE to is not null
    RETURN from, rel, to 
    

    Result:

    enter image description here

    Creating the nodes WITH relationship weights can be done this way. Unfortunately, apoc.nodes.collapse is not returning relationship weights that you described. But apoc.collapse can count the number of nodes that are merged using countMerge:true.

    MATCH (p:Person)-[:R]->(c:Person)
    WITH c, collect(p) as subgraph, count(distinct p) AS relweight
    WITH c.department as relto, [s in subgraph|s.department][0] as relfrom, relweight 
    MERGE (d1:Department {name: relfrom})
    MERGE (d2:Department {name: relto})
    MERGE (d1)-[r:newR{wt: relweight}]->(d2)
    RETURN d1, d2, r
    

    Result:

    enter image description here