简体   繁体   中英

Get complete path from a sequence of nodes from Neo4j Graph database with Cypher

I am storing a sequence of nodes, where a node is related to the previous node in the sequence as well as another node representing an 'object'. So for example I might have this sequence:

(S1)<-[r]-(S2)<-[r]-(S3)<-[r]-(S4)

And then each of the nodes in the sequence are related to another node for eg:

(S1)-[r]->(O1)
(S2)-[r]->(O2)
(S3)-[r]->(O1)
(S4)-[r]->(O3)

In this example both S1 and S3 are related to O1.

What I want to achieve is to specify the starting point as 'O1' and be able to get the complete path from S1 to S4 in the example above.

I was able to achieve this by adding a property in S1 called 'start' and another in S4 called 'end', to represent the start and end of a sequence and use this query to get the complete sequence only:

MATCH (O:Obj{name:'O1'}), 
path=(O)<-[:OBJECT]-(first:SEQ)<-[:PREV*]-(last:SEQ) 
WHERE has(first.start) 
AND has(last.end) 
return path

However, I was wondering if there is a better way to achieve this without the 'start' and 'end' properties. The problem I'm encountering when not using the properties is that the sequence is broken down so instead of one sequence I get:

(S1)<-[r]-(S2)
(S1)<-[r]-(S2)<-[r]-(S3)
(S1)<-[r]-(S2)<-[r]-(S3)<-[r]-(S4)
(S3)<-[r]-(S4)

Is it possible in any way to get the complete sequence only?

You can just require that last be at the "end of the chain":

MATCH path=(:Obj {name:'O1'})<-[:OBJECT]-(:SEQ)<-[:PREV*]-(last:SEQ)
WHERE NOT (last)<-[:PREV]-(:SEQ)
RETURN path

Yes you can. You just need to order the resulting paths by size in descending order and return only the longest one.

match p=(:Obj {name:'O1'})<-[:REL]-(:SEQ)<-[:PREV*]-(:SEQ)
with p, size(nodes(p)) as seq_length
order by seq_length desc
limit 1
return tail(nodes(p))

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