neo4j cypher深度搜索第一

时间:2016-05-29 10:07:34

标签: neo4j cypher

我有一个类似树状的图表,如下所示enter image description here

现在假设我从根节点 R 开始,并希望从 1 找到所有路径到最近的类型 B 节点。在示例图中,结果应为

path-1: 1,2
path-2: 1,3,6,10,13
path-3: 1,3,7,10,13

我该怎么做?

1 个答案:

答案 0 :(得分:2)

将节点类型保留在标签 - (:A)(:B)中,节点之间的关系类型为' connect'。

// Find all paths from Root to all B-nodes
MATCH (A:A {name:1}), p = (A)-[:connect*]->(B:B)

  // Get all node labels for each path
  WITH A, p, extract( n in nodes(p) | labels(n) ) as pathLabels

  // We find the number of occurrences of B-node in each path
  WITH A, p, reduce( bCount = 0, Labels in pathLabels | 
                     CASE WHEN 'B' IN Labels THEN 1 ELSE 0 END + bCount
             ) as bCount

  // Return only the path in which the B-node is in the end of the path
  WHERE bCount = 1
RETURN p

示例数据查询:

MERGE (A1:A {name:1})-[:connect]-(B2:B {name:2}) MERGE (A1)-[:connect]-(A3:A {name:3}) MERGE (B2)-[:connect]-(A4:A {name:4}) MERGE (B2)-[:connect]-(A5:A {name:5}) MERGE (A4)-[:connect]-(B8:B {name:8}) MERGE (B8)-[:connect]-(A11:A {name:11}) MERGE (B8)-[:connect]-(A12:A {name:12}) MERGE (A5)-[:connect]-(A9:A {name:9}) MERGE (A3)-[:connect]-(A6:A {name:6}) MERGE (A3)-[:connect]-(A7:A {name:7}) MERGE (A6)-[:connect]-(A10:A {name:10}) MERGE (A7)-[:connect]-(A10) MERGE (A10)-[:connect]-(B13:B {name:13}) RETURN *

更新(不搜索A-type个节点):

// Find all paths from Root to all not A-nodes 
MATCH (A:A {name:1}), p = (A)-[:connect*]->(B) WHERE NOT 'A' IN labels(B)

  // Get all node labels for each path
  WITH A, p, extract( n in nodes(p) | labels(n) ) as pathLabels

  // We find the number of occurrences of A-node in each path
  WITH A, p, reduce( aCount = 0, Labels in pathLabels | 
                     CASE WHEN 'A' IN Labels THEN 1 ELSE 0 END + aCount
             ) as aCount

  // Return only the path in which the count of A-node 
  // is 1 less the total number of nodes in the path.
  WHERE aCount = length(p)
RETURN p