Search code examples
neo4jcypher

Quantifying path patterns


I am learning neo4j right now and understood/created the relationships between the nodes. I am trying to understand the quantifying path patterns. It seems like I was able to write the general queries to figure out the relationships between the nodes.

Consider this snapshot for the discussion:

enter image description here

'Purple' are the Person nodes and 'red' nodes are the Marriage nodes. I wrote this path pattern to get me all the relationship paths:

match ((p:Person)<-[:IS_MAN_OF]-(m:Marriage)-[:IS_SON_OF]->(p1:Person)){1,} return p, p1

This returns me all the combinations at all the levels like

Atma Ram - Tek Chand
Atma Ram - Mukesh
Tek Chand - Hemant
Tek Chand - Rocky
Mukesh - Dimpy

Alright. This make complete sense to me.

What does not make sense is that If I add an where clause in my quantifying pattern, it does not give me nodes at more than 1 level. This is the patterns I used along with where.

 match ((p:Person where p.name = 'Atma ram')<-[:IS_MAN_OF]-(m:Marriage)-[:IS_SON_OF]->(p1:Person)){1,} return p, p1

I am curios to know the reason as to why does it not work for all levels. Also, what shall I write to get all the nodes at all levels even for an where clause.

Thank you.

Tried giving different combinations of min & max in the curly braces.


Solution

  • It does not work on all levels because you are anchoring the first node OF EACH iteration to be ‘Atma ram’. That works for the first iteration, but the second (and following) iterations will not start with the ‘Atma ram’ node, so you only get results from the first one.

    I guess you want to anchor the starting point of the whole repetitions, not the starting point of every iteration. To do that, you need to extract the starting point out of the repetition parenthesis:

     MATCH (s:Person where s.name = 'Atma ram') ((p)<-[:IS_MAN_OF]-(m:Marriage)-[:IS_SON_OF]->(p1:Person)){1,} return p, p1
    

    (s:Person where s.name = 'Atma ram') is the anchor, it matches the start node, and on the first iteration, is joined with (p) (see equijoins in the docs). On the second iteration, the end node of the first iteration (p1) will join with the first node of the second iteration (p), allowing the path to repeat, and so on.

    If you look at the documentation, Concepts, Quantified Path Pattern section, you’ll get a more detailed example that anchors both the start end the end station of a rail trip. You can anchor the end of repetitions similarly as you can anchor the start.

    Hope it helps