Janiiik
Janiiik

Reputation: 1338

How do i get number of same relationships between two nodes with Cypher

enter image description here

Now I need query that returns ancestor nodes of Borko with number of relationship hops.. Something like this:

2nd part of question : If we include mother relationships, what would query look like? result should be something like:

Upvotes: 2

Views: 112

Answers (1)

Gabor Szarnyas
Gabor Szarnyas

Reputation: 5047

I used this snippet to recreate your data set:

CREATE
   (:Person {name: 'Jan'})-[:Father]->
   (:Person {name: 'Mirko'})-[:Father]->
   (:Person {name: 'Cupko'})-[:Father]->
   (:Person {name: 'Borko'})

You should save the path and use the length of path to get the number of hops:

MATCH p=(b:Person {name: 'Borko'})<-[:Father*]-(n)
RETURN n, length(p)

This returns:

╒════════════════╤═══════════╕
│"n"             │"length(p)"│
╞════════════════╪═══════════╡
│{"name":"Cupko"}│1          │
├────────────────┼───────────┤
│{"name":"Mirko"}│2          │
├────────────────┼───────────┤
│{"name":"Jan"}  │3          │
└────────────────┴───────────┘

For the second part, you can use the relationships function:

MATCH p=(b:Person {name: 'Borko'})<-[:Father|Mother*]-(n)
WITH p, relationships(p) AS rels, n
RETURN n, length(p) AS hops, type(rels[length(rels)-1]) AS type

This returns:

╒════════════════╤══════╤════════╕
│"n"             │"hops"│"type"  │
╞════════════════╪══════╪════════╡
│{"name":"Cupko"}│1     │"Father"│
├────────────────┼──────┼────────┤
│{"name":"Mirko"}│2     │"Father"│
├────────────────┼──────┼────────┤
│{"name":"Jan"}  │3     │"Father"│
└────────────────┴──────┴────────┘

Of course, you can use case expressions to convert the name of the relationship the appropriate type, e.g. CASE type(rels[length(rels)-1]) WHEN 'Father' THEN 'Dad' WHEN 'Mother' THEN 'Mom' END AS role

Upvotes: 4

Related Questions