在neo4j cypher中查找节点及其所有传入和传出节点

时间:2015-04-07 22:48:24

标签: neo4j cypher

我想编写一个获取节点的单个cypher查询及其所有传入和传出关系。

例如,假设我们有节点N,有两个传入关系:(I1) - [IR1] - >(N)和(I2) - [IR2] - >(N),以及两个传出关系: (N) - [OR1] - >(O1)和(N) - [OR2] - >(O2)。

我想要一个可以产生的查询:

{
    node: { properties of N },
    incoming: [
        { relationship: IR1, node: { properties of I1 } },
        { relationship: IR2, node: { properties of I2 } }
    ],
    outgoing: [
        { relationship: OR1, node: { properties of O1 } },
        { relationship: OR2, node: { properties of O2 } }
    ]
}

我能得到的最接近的密码查询是:

match (node { criterial })
match (incoming)-[incomingr]->(node)
match (node)-[outgoingr]->(outgoing)
return node, collect(distinct incoming), collect(distinct outgoing)

但它不包含类型(传入者)和类型(传出者)。

返回路径也没有给我我想要的东西,因为它包含关系属性而不是类型,更不用说它返回(节点)的许多重复副本。

我知道我可以简单地

return node, incoming, outgoing, type(incomingr), type(outgoingr)

获取所有内容然后通过JSON处理以获得我想要的内容,但随着关系数量的增加,返回的数据将变得太大,因为它返回所有传入路径和传出路径的组合。 它只是不整洁。

1 个答案:

答案 0 :(得分:4)

基于http://console.neo4j.org中的标准演示数据集,以下查询接近您想要实现的目标:

MATCH (n:Crew)
WHERE n.name='Morpheus'
MATCH ()-[rin]->(n)-[rout]->()
WITH n, collect(DISTINCT 
       { relationship:type(rin), 
         node: startNode(rin)
       }) AS incoming, 
collect(DISTINCT 
       { relationship:type(rout), 
         node: endNode(rout)
       }) AS outgoing
RETURN { node: n, incoming: incoming, outgoing: outgoing } AS result
相关问题