1
votes

I am using the below code to return all nodes and edges (3 level of depth) from Neo4j and format the response as GraphJSON. I am then using some D3 code to visualize the Graph on my front end.

This works fine for nodes that have at least one relationship or edge. However, I also have some nodes that are not connected to any other nodes. I want to also include these nodes in the response of the query.

Any suggestions how I can modify the code below so that it also picks up floating nodes that are not connected by a relationship to the graph?

OPTIONAL MATCH path = (x:entity)-[*..3 {current:true}]->(:entity)

UNWIND nodes(path) as node
UNWIND rels(path) as rel

WITH collect(distinct node) as nodes,
     collect(distinct rel) as rels
WITH apoc.coll.toSet( [n in nodes WHERE n is not null | { id: id(n),label: labels(n),type:"",metadata: properties(n)  } ]) as nodes, 

apoc.coll.toSet([r in rels WHERE r is not null  | { id: id(r),source: id(startNode(r)),relation: type(r),target: id(endNode(r)), directed: "true"  } ]) as rels

RETURN { graph: { type:"",label: "",directed: "true",nodes: nodes,edges: rels, metadata:{ countNodes: size(nodes),countEdges: size(rels) } } } as graph;

Thanks a lot,

1

1 Answers

1
votes

You can add collections together using the + operator, so after you've collected nodes and rels, MATCH to the floating nodes you want to include, collect them, add the collection to your nodes collection, and finish up your query.