简体   繁体   English

使用Neo4j Cypher获取没有第一个或最后一个节点的最长路径

[英]Using Neo4j Cypher to obtain the longest path without the first or last node

I have a forest of nodes and relationships. 我有一个节点和关系的森林。 Similar to the following: 类似于以下内容:

N1-sends->N2-sends->N3-sends->N4 N1-sends-> N2-sends-> N3-sends-> N4

N5-sends->N6-sends->N7-sends->N8 N5-sends-> N6-sends-> N7-sends-> N8

N9-sends->N10-sends->N11-sends->N12-sends->N13 N9-sends-> N10-sends-> N11-sends-> N12-sends-> N13

I want to write a Cypher query that returns the 3 paths, without the first or last item. 我想写一个Cypher查询返回3个路径,没有第一个或最后一个项目。 The nodes that are NOT at the beginning or end of the paths already have a property("middle", "true"), so that makes it easier. 不在路径开头或结尾的节点已经具有属性(“中间”,“真”),因此更容易。

A problem that I have encountered is that Cypher returns the path and every SUBSET of the path as well. 我遇到的一个问题是Cypher还返回路径和路径的每个SUBSET。 For example it returns n10->n11-> and n11->n2, and n10->n11->n12, .... which is not what I want. 例如,它返回n10-> n11->和n11-> n2,以及n10-> n11-> n12,....这不是我想要的。

Instead I just want the results to be an array of 3, where inside each I have: 相反,我只希望结果是一个3的数组,其中每个我有:

n2->n3 N2-> N3

n6->n7 N 6 - > N7

n10->n11->n12 N10-> n11-> N12

and thats it. 就是这样。

The queries that I have came up with are: (first one has syntax errors): 我提出的查询是:(第一个有语法错误):

START n=node(*) MATCH p=()-[*]->i-[*]->() WHERE has(i.middle) 
WITH COLLECT(p) AS pa, MAX(length(p)) AS maxLength, NODES(p) AS pn
FILTER(path IN pa WHERE length(path)=maxLength) AS longestPaths 
RETURN DISTINCT FILTER(x IN longestPaths WHERE exists(x.middle)) 

and

START n=node(*) MATCH p=()-[*]->i-[*]->() 
WHERE has(i.middle)  
RETURN DISTINCT filter(x IN NODES(p) WHERE exists(x.middle)) as O

The second one returns the paths without the first and last node, but it returns duplicated nodes, because it returns subsets of path as well.. 第二个返回没有第一个和最后一个节点的路径,但它返回重复的节点,因为它也返回路径的子集。

Thank you. 谢谢。

This might do what you want: 这可能会做你想要的:

MATCH (n)-[:sends*]->(m)
WHERE NOT ( ()-[:sends]->(n) OR (m)-[:sends]->() )
RETURN NODES(p)[1..-1] AS middleNodes;

The WHERE clause eliminates sub-paths (ie, paths that are part of a longer path). WHERE子句消除子路径(即,作为较长路径的一部分的路径)。 The NODES(p)[1..-1] syntax returns the second through next-to-last nodes in each path. NODES(p)[1..-1]语法返回每个路径中的第二个到倒数第二个节点。

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

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