【问题标题】:Need only common nodes across multiple paths - Neo4j Cypher只需要跨多个路径的公共节点 - Neo4j Cypher
【发布时间】:2016-02-05 17:22:59
【问题描述】:

sMy Cypher 查询查找多个起始节点的公共子节点。每个路径只有它的节点 ID 被提取并返回,导致每个路径中有数百行。请参见 p1 和 p2 示例(仅显示 3 行和两个起点)。

Match p1=(n1:node{name:"x" })-[r:sub*]->(i)), p2=(n2:node{name:"y" })-[r:sub*]->(i))
RETURN DISTINCT i, extract(a IN nodes(p1)| a.id) as p1, extract(b IN nodes(p2)| b.id) as p2

----RESULTS----

p1=1,4,3
p1=1,8,3
p1=1,8,9,3 

p2=6,7,3
p2=6,5,9,3
p2=6,7,10,3

我想要的是在查询期间与密码中的路径相交,这样我之后就不必这样做了。在 php 中,我将使用以下方法进行迭代:

$result = array_intersect($p1,$p2);

这将从上面的示例返回 9,3,因为它们是所有路径共享的唯一公共节点。有没有办法在 Cypher 中做到这一点,这样我就不会返回数百行?

谢谢!

【问题讨论】:

    标签: path neo4j cypher intersect


    【解决方案1】:

    我相信这会满足您的需求。

    这是正在考虑的数据的图片。

    // match the two different paths with the common ending i
    match p1=(n1:Node {name: 1 })-[:SUB*]->(i)
    , p2=(n2:Node {name: 6 })-[:SUB*]->(i)
    
    // collect both sets of paths for every 
    with i, collect(p1) as p1, collect(p2) as p2
    
    // recombine the nodes of the first path(s) as distinct collections of nodes
    unwind p1 as p
    unwind nodes(p) as n
    with i, p2, collect( distinct n ) as p1
    
    // recombine the nodes of the second path(s) as distinct collections of     
    unwind p2 as p
    unwind nodes(p) as n
    with i, p1, collect( distinct n ) as p2
    
    // return the common ending node with the nodes common to each path
    return i, [n in p1 where n in p2 | n.name] as n
    

    编辑:更新解决方案以包含第三条路径

    // match the two different paths with the common ending i
    match p1=(n1:Node {name: 1 })-[:SUB*]->(i)
    , p2=(n2:Node {name: 6 })-[:SUB*]->(i)
    , p3=(n3:Node {name: 4 })-[:SUB*]->(i)
    
    // collect both sets of paths for every 
    with i, collect(p1) as p1, collect(p2) as p2, collect(p3) as p3
    
    // recombine the nodes of the first path(s) as distinct collections of nodes
    unwind p1 as p
    unwind nodes(p) as n
    with i, p2, p3, collect( distinct n ) as p1
    
    // recombine the nodes of the second path(s) as distinct collections of     
    unwind p2 as p
    unwind nodes(p) as n
    with i, p1, p3, collect( distinct n ) as p2
    
    // recombine the nodes of the third path(s) as distinct collections of     
    unwind p3 as p
    unwind nodes(p) as n
    with i, p1, p2, collect( distinct n ) as p3
    
    // return the common ending node with the nodes common to each path
    return i, [n in p1 where n in p2 and n in p3 | n.name] as n
    

    【讨论】:

    • 谢谢,这似乎有效。我无法更改返回线以接受两个以上的路径,例如p3 p4 等。我怎样才能结合两个以上?谢谢!
    • 我添加了一个 3 路径解决方案。如果我有时间,我会看看我是否可以为您提供一个通用的 n 路径解决方案。
    • 非常感谢这个戴夫 - 你让它看起来如此简单!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-27
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 2020-03-04
    • 1970-01-01
    相关资源
    最近更新 更多