pYr0
pYr0

Reputation: 169

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

Upvotes: 4

Views: 10538

Answers (2)

Luanne
Luanne

Reputation: 19373

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

Upvotes: 13

Thomas Fenzl
Thomas Fenzl

Reputation: 4392

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

Upvotes: 2

Related Questions