简体   繁体   中英

Get Path Length from Cypher Query

So, Say that I've got a list of nodes like so:

A -> B -> C -> D -> ...

I want to add node F onto the beginning of this list. To complicate this pattern, I can be given a reference to any node on this list as the "starting point," from which I will need to derive the starting point. For example, I could be given a reference to node "C", and need to derive an algorithm that will return a reference to A.

I figure this should be able to be done with a query such as

    START n = node(*), a = node(*)
    MATCH a -[:LINKED*]> n
    WHERE n.id! = <ID>
    RETURN a

If I could sort the relationships by length, I could simply take the longest path as the first node in the relationship, and go along my merry way. Trouble is, I can't figure out how to order the results by path length. I figure that it must be possible, I'm just missing a small query command. Any takers?

-pYr0

Length is function: http://docs.neo4j.org/chunked/stable/query-functions-scalar.html#functions-length

START n = node(*), a = node(*)
MATCH p=a -[:LINKED*]-> n
WHERE n.id! = <ID>
RETURN a
ORDER BY length(p) desc

If you want the head of the list, you can also match with an optional relationship leading into your candidate node. If the relation does not exist, you're there.

Assuming that you got the ID of some node in the chain:

START n = node(<ID>)
MATCH () -[r?:LINKED]-> a -[:LINKED*]-> n
WHERE r = null
RETURN a

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