Neo4j - extract all subgraphs from neo4j database

冷暖自知 提交于 2019-12-11 18:47:44

问题


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"}]│
└───────┴──────────────────────────────────────────────────┘


来源:https://stackoverflow.com/questions/53447957/neo4j-extract-all-subgraphs-from-neo4j-database

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!