Get connected graphs in neo4j by using cypher quer

2019-04-16 15:57发布

How can we modify the cypher query so that it can give all the connected graphs (means the set of nodes and relationships that are connected to each other directly or indirectly) as a result for the query.

OR

Can I use traversal framework for my requirement?

The use case is: I need to get all the connected graphs from neo4j and store their information as an "cluster" in other database.1 group of connected graph = 1 cluster. I need to separate the connected graphs and then store the aggregate of some of the properties of nodes/relations and store it in other db.

I am using REST to interact with neo4j db.

标签: neo4j cypher
2条回答
放我归山
2楼-- · 2019-04-16 16:17

It won't be fast though.

A dedicated algorithm in Java will be much faster collecting that data.

Idea for Cypher (which probably has really bad complexity and doesn't yet work):

  1. get all nodes
  2. for each node
  3. if it is connected to any first node of a connected graphs (shortestPath) skip it, else collection of all end nodes of all paths

.

MATCH (n) 
WITH COLLECT(n) as nodes
RETURN REDUCE(graphs = [], n in nodes | 
  case when 
    ANY (g in graphs WHERE shortestPath((n)-[*]-(head(g))) 
         then graphs 
         else graphs + [[p in (n)-[*0..]-() | nodes(p)[length(p)-1]]]
         end ))
查看更多
相关推荐>>
3楼-- · 2019-04-16 16:28

@michael, I've modified a bit your query. Now it works on my data. The variant I'm posting keeps only one element per connected component. This is convenient if one is not interested in having the actual member of the components but still wants to be able to retrieve the members of each component.

@manish, I know that it's late but, maybe, you could have stored the component representatives in your new database, rather than all their members.

MATCH (n) 
WITH COLLECT(n) as nodes
RETURN REDUCE(graphs = [], n in nodes | 
  case when 
    ANY (g in graphs WHERE shortestPath( (n)-[*]-(g) ) ) 
    then graphs 
    else graphs + [n]
    end )
查看更多
登录 后发表回答