简体   繁体   中英

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

在此处输入图片说明

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

  • Cupko ... 1
  • Mirko ... 2
  • Jan ... 3

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

  • Cupko ... dad ... 1
  • SomeFemale ... mom ... 1
  • Mirko ... dad ... 2
  • SomeFemale2 ... mom ... 2

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, eg CASE type(rels[length(rels)-1]) WHEN 'Father' THEN 'Dad' WHEN 'Mother' THEN 'Mom' END AS role

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM