1
votes

I am trying to search for a specific node by id and then return all nodes and relationships that are 1 or 2 hops away from that node. I am also trying to format the results as JSON for use in D3. Thanks to some help on a previous post from @william-lyon I managed to get the query working for 1 hop. My problem now is that when I extend it to 2 hops I get duplicates back when I want to only have distinct nodes and relationships. I have tried to use the RETURN(DISTINCT X) FUNCTION but I can't get it to work.

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

Thanks a lot

1

1 Answers

0
votes

Does something like this meet your needs? It just flatten the collections you were returning and recombines the distinct entities of each.

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