Tony Ennis
Tony Ennis

Reputation: 12289

Find the nodes in a Neo subgraph

I have a cyclic subgraph. I would like to know all the relationships in that subgraph. I don't know how deep the subgraph is, nor do I want to hardcode any relationship types.

The best thing I have found so far is driven by this snippet.

match(n:X)-[r*]->(m)

from r, I can find what I need. However, even for a small subgraph the cardinality of r* can be 30k or more. There is no point for Neo to calculate every path through the subgraph. I really just need the nodes or the individual relationships (preferred).

What is a way to just get the individual relationships in a subgraph? We're using Cypher.

Upvotes: 0

Views: 232

Answers (2)

Martin Preusse
Martin Preusse

Reputation: 9369

You can collect all nodes in a connected components with a breadth first or depth first search without filter.

The neo4j REST API has a traversal endpoint which can be used to do exactly that. It's not a Cypher query, but it could solve your problem: http://neo4j.com/docs/stable/rest-api-traverse.html

You can POST something like this against a node, there are options to only take unique nodes. Not sure but this might help with a cyclic graph.

{
  "order" : "breadth_first",
  "uniqueness" : "node_global",
  "return_filter" : {
    "language" : "builtin",
    "name" : "all"
    },
  "max_depth" : 20
}

Upvotes: 1

cybersam
cybersam

Reputation: 66957

Cypher provides no way to get all the relationships in a subgraph without following the paths. Besides, it has to explore those paths anyway in order to figure out what nodes and relationships belong to the subgraph.

To ensure that you get each relationship in a cyclic subgraph only once, you can do this:

MATCH p=(:Foo)-[*]->()
WITH RELATIONSHIPS(p) AS ps
UNWIND ps AS p
RETURN DISTINCT p;

Note, however, that variable-length path queries with no upper bound can be very expensive and may end up running "forever".

Alternate approach

If you can identify all the nodes in the desired subgraph, then there can be a more performant approach.

For example, let's suppose that all the nodes in the desired subgraph (and only those nodes) have the label X. In that case, this quick query will return all the relationships in the subgraph:

MATCH p=(:Foo)-[r]->()
RETURN r;

Upvotes: 1

Related Questions