从cypher返回不同的节点和关系,格式为JSON

时间:2017-03-01 10:44:19

标签: neo4j cypher

我试图通过id搜索特定节点,然后返回距离该节点1或2跳的所有节点和关系。我也试图将结果格式化为JSON以用于D3。感谢@ william-lyon上一篇文章的一些帮助,我设法让查询工作了1跳。我现在的问题是,当我将它扩展到2个跃点时,当我想要只有不同的节点和关系时,我会得到重复。我曾尝试使用RETURN(DISTINCT X)功能,但我无法使其工作。

MATCH (l0) -[r1]-> (l1) -[r2]-> (l2)
WHERE ID(l0) = 65
RETURN 
    [
           {
                type: "node",
                id: id(l0),
                labels: labels(l0),
                props: apoc.map.fromPairs([key IN keys(l0) | [key, l0[key]]])
            },
            {
                type: "node",
                id: id(l1),
                labels: labels(l1),
                props: apoc.map.fromPairs([key IN keys(l1) | [key, l1[key]]])
            },
            {
                type: "node",
                id: id(l2),
                labels: labels(l2),
                props: apoc.map.fromPairs([key IN keys(l2) | [key, l2[key]]])
            }
    ] as nodes,
    [
            { 
                startNodeId: ID(startNode(r1)),
                endNodeId: ID(endNode(r1)), 
                relType: type(r1)
            },
            { 
                startNodeId: ID(startNode(r2)),
                endNodeId: ID(endNode(r2)), 
                relType: type(r2)
            }
] as relationships

非常感谢

1 个答案:

答案 0 :(得分:0)

这样的事情能满足您的需求吗?它只是压缩你返回的集合,并重新组合每个集合的不同实体。

MATCH (l0:Node {name: 'N1'}) -[r1]-> (l1:Node) -[r2]-> (l2:Node)
WITH [
       {
            type: "node",
            id: id(l0),
            labels: labels(l0),
            props: apoc.map.fromPairs([key IN keys(l0) | [key, l0[key]]])
        },
        {
            type: "node",
            id: id(l1),
            labels: labels(l1),
            props: apoc.map.fromPairs([key IN keys(l1) | [key, l1[key]]])
        },
        {
            type: "node",
            id: id(l2),
            labels: labels(l2),
            props: apoc.map.fromPairs([key IN keys(l2) | [key, l2[key]]])
        }
] as nodes,
[
        { 
            startNodeId: ID(startNode(r1)),
            endNodeId: ID(endNode(r1)), 
            relType: type(r1)
        },
        { 
            startNodeId: ID(startNode(r2)),
            endNodeId: ID(endNode(r2)), 
            relType: type(r2)
        }
] as relationships
UNWIND nodes as node
UNWIND relationships as relationship
RETURN collect(distinct node) as nodes, collect(distinct relationship) as relationships