如何在neo4j中返回路径的第二个节点?

时间:2017-01-14 06:38:54

标签: neo4j cypher

我有查询路径的查询:

MATCH p =(o:Order)-[r:seeks*2..8]->(o:Order)
WHERE o.Name="000089"
  AND ALL(x IN tail(nodes(p))
          WHERE SINGLE(y IN tail(nodes(p))
                       WHERE x=y))
RETURN extract(n IN nodes(p)| n.Name) AS OrderID, length(p) 
ORDER BY length(p)

我的输出是:

OrderID长度(p)

  1. [000089, 000091 ,000089] 2
  2. [000089, 000093 ,000090,000089] 3
  3. [000089, 000091 ,000096,000095,000090,000089] 5
  4. [000089, 000091 ,000096,000097,000093,000090,000089] 6
  5. [000089, 000091 ,000098,000092,000095,000090,000089] 6
  6. [000089, 000093 ,000090,000096,000097,000091,000089] 6
  7. [000089, 000093 ,000094,000092,000097,000091,000089] 6
  8. 所以,我还想要在每条路径上返回第二个节点,如(上面用粗体标记的节点):

    1. [000091]
    2. [000093]
    3. [000091]
    4. [000091]
    5. [000091]
    6. [000093]
    7. [000093]

1 个答案:

答案 0 :(得分:1)

我创建了一个用于实验的简单数据集:

CREATE
   (o1:Order {Name: '0089'})-[:seeks]->
   (o2:Order {Name: '0090'})-[:seeks]->
   (o3:Order {Name: '0091'})-[:seeks]->(o1)

这是一个(o1)->(o2)->(o3)->(o1)圈。

使用nodes函数提取路径上的节点并将列表索引到第二个节点。 Cypher中的列表从零开始编号。

MATCH p=(o:Order {Name: '0089'})-[r:seeks*2..8]->(o:Order)
RETURN nodes(p)[1]

或者,您可以在不使用路径变量并获取第一个关系的endNode的情况下执行此操作(请注意,这仅适用于定向关系):

MATCH (o:Order {Name: '0089'})-[r:seeks*2..8]->(o:Order)
RETURN endNode(r[0])