简体   繁体   English

使用Cypher从Neo4j Graph数据库中的一系列节点获取完整路径

[英]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. 在此示例中,S1和S3都与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. 我要实现的是将起始点指定为“ O1”,并能够获得上述示例中从S1到S4的完整路径。

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: 通过在S1中添加一个称为“开始”的属性,并在S4中添加一个称为“结束”的属性,我能够实现这一点,以表示序列的开始和结束,并使用此查询仅获取完整的序列:

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. 但是,我想知道如果没有'start'和'end'属性,是否有更好的方法来实现这一目标。 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": 您可以只要求last位于“链的末端”:

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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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