首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >neo4j密码深度第一次搜索

neo4j密码深度第一次搜索
EN

Stack Overflow用户
提问于 2016-05-29 10:07:34
回答 1查看 264关注 0票数 1

我有一个树状的图表,如下所示

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

代码语言:javascript
复制
path-1: 1,2
path-2: 1,3,6,10,13
path-3: 1,3,7,10,13

我该怎么做?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-05-29 11:08:30

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

代码语言:javascript
复制
// 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

示例数据查询:

代码语言:javascript
复制
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节点):

代码语言:javascript
复制
// 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
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37508603

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档