Subgraph extraction in neo4j

I have a large network stored in Neo4j. Based on the specific root of the node, I want to extract a subgraph around this node and save it somewhere else. So, I need a set of nodes and edges that match my filter criteria.

Afaik there is no turnkey solution. There is a graph corresponding to the component available , but it only works for perfect matches. The Neo4j API only defines a graph traversal that I can use to determine which nodes / edges should be visited:

Traverser exp = Traversal
    .description()
    .breadthFirst()
    .evaluator(Evaluators.toDepth(2))
    .traverse(root);

Now I can add all nodes / edges to sets for all paths, but this is very inefficient. How would you do that? Thank!

EDIT Does it make sense to add the last node and the last relation of each traversal to the subgraph?

+5
source share
3 answers

I solved this by building an induced subgraph based on all the traversal endpoints.

Building a subgraph from the set of last nodes and edges of each traversal does not work, because edges that are not part of the shortest paths will not be included.

The code snippet is as follows:

Set<Node> nodes = new HashSet<Node>();
Set<Relationship> edges = new HashSet<Relationship>();

for (Node n : traverser.nodes())
{
    nodes.add(n);
}

for (Node node : nodes)
{
    for (Relationship rel : node.getRelationships())
    {
        if (nodes.contains(rel.getOtherNode(node)))
            edges.add(rel);
    }
}

Each edge is added twice. Once for an outgoing node and once for an incoming node. Using Set, I can provide it in the collection only once.

It is only possible to iterate over incoming / outgoing edges, but it is unclear how the loops are processed (edge ​​from node to itself). What category do they belong to? This snippet does not have this problem.

+2

, http://docs.neo4j.org/chunked/snapshot/cypher-query-lang.html, matchin .

subgraph Cypher, Cypher , SQL, -

start n=node:node_auto_index(name='Neo') 
match n-[r:KNOWS*]-m 
return "create ({name:'"+m.name+"'});"

http://console.neo4j.org/r/pqf1rp

+3

See database reset in cypher statement

dump START n=node({self}) MATCH p=(n)-[r:KNOWS*]->(m) RETURN n,r,m;

There is also an example for importing a subgraph of the first database (db1) into the second (db2).

0
source

All Articles