Neo4j - extract all subgraphs from neo4j database

2019-08-28 04:55发布

问题:

I have a similar question to the one asked here, however, the solution proposed didn't work for me.

My Neo4j database has a lot of sub-graphs, each one of them contains varying number of nodes.

I would like to extract some kind of a list which will contain all sub-graphs separated.

In the example given, I would like to get 3 groups, where each group contains all the nodes in the sub-graph which the group represents.

How can I get all groups of nodes by Cypher query?

All the solutions that I have found for this problem require "root" node which I don't have in this case.

回答1:

You could use graph algorithms plugin and specifically connected components algorithm to label all the isolated subgraphs in your graph and then export them and group them later when exported by set id.

Example:

create a sample graph

MERGE (nAlice:User {id:'Alice'})
MERGE (nBridget:User {id:'Bridget'})
MERGE (nCharles:User {id:'Charles'})
MERGE (nDoug:User {id:'Doug'})
MERGE (nMark:User {id:'Mark'})
MERGE (nMichael:User {id:'Michael'})

MERGE (nAlice)-[:FRIEND]->(nBridget)
MERGE (nAlice)-[:FRIEND]->(nCharles)
MERGE (nMark)-[:FRIEND]->(nDoug)
MERGE (nMark)-[:FRIEND]->(nMichael);

Run connected components (unionFind) algorithm and return nodes in the same subgraph:

CALL algo.unionFind.stream('User', 'FRIEND', {})
YIELD nodeId,setId
RETURN setId,collect(algo.getNodeById(nodeId)) AS nodes_from_specific_subgraph

This will return:

╒═══════╤══════════════════════════════════════════════════╕
│"setId"│"specific_subgraph"                               │
╞═══════╪══════════════════════════════════════════════════╡
│4      │[{"id":"Doug"},{"id":"Mark"},{"id":"Michael"}]    │
├───────┼──────────────────────────────────────────────────┤
│0      │[{"id":"Alice"},{"id":"Bridget"},{"id":"Charles"}]│
└───────┴──────────────────────────────────────────────────┘


标签: neo4j cypher