Reputation: 135
I'm learning Neo4j while playing with a dog pedigree graph. The following query gives me all nodes that has a :PARENT_OF relationship to more than one node.
match (n)-[r:PARENT_OF]->() with n, count(r) as rel_cnt where rel_cnt > 1 return n;
For the example graph this yields two nodes. Now I want to combine this with the next query, to get the path between a fixed child (A) and a variable parent (the result from the first query):
match p =(child:Dog {name: "A"})<-[:PARENT_OF*0..]-(parent:Dog {name: "X"}) return p
I have looked at the WITH clause, but cannot wrap my head around it. Any suggestions for how to feed the results of the first query to the second one is really appreciated!
Please see this Neo4j console for a sample graph http://console.neo4j.org/?id=6nm2e3
Upvotes: 0
Views: 405
Reputation: 66999
It is unnecessary (and inefficient) to first get all parents with more than 1 child just to get the paths from a specific child to its parents who have more than 1 child.
Instead, you could just get the specific child, and see how many children each of its parents have. For example:
MATCH p = (child:Dog {name: "A"})<-[:PARENT_OF]-(n)
WHERE SIZE((n)-[:PARENT_OF]->()) > 1
RETURN p;
Upvotes: 1
Reputation: 30397
One quick suggestion, you can use a trick to get the degree of a relationship type from a node, which is much more efficient than expanding a relationship and getting its count.
Also, in this particular case, you don't have to use WITH, you can reuse your n
variable right away.
MATCH (n)
WHERE size((n)-[r:PARENT_OF]->()) > 1
MATCH p =(child:Dog {name: "A"})<-[:PARENT_OF*0..]-(n) return p
As for WITH, it's used to redefine which variables are in scope for the next part of your query, and it's usually the place where you can alter the result records, such as by projecting properties from nodes and relationships, making function calls, and more.
Upvotes: 1