0

I took help from this answer it works fine but not for isolated nodes means single node with no relations (child nodes). What i am getting in this case not even that one node. Kindly help me i am beginner to neo4j, it would be great favour

answer link

OPTIONAL MATCH path = (x)-[*0..100]->()       
WHERE ID(x) = 65
UNWIND nodes(path) as node
UNWIND rels(path) as rel

WITH collect(distinct node) as nodes,collect(distinct rel) as rels
// WITH apoc.coll.flatten(collect(nodes(path))) as nodes, apoc.coll.flatten(collect(relationships(path))) 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

Awais Khan
  • 175
  • 1
  • 15

1 Answers1

1

The problem is this: UNWIND rels(path) as rel

UNWINDing a collection means taking that record, and changing it into a record per element in the collection, it multiplies the records. When the collection is empty (there will be no relationships for an isolated node), that's multiplying times zero...it wipes out the records with empty collections.

You can use a CASE statement to substitute a collection with null instead of an empty collection (the null will be wiped out when you collect again). That keeps the record when you UNWIND.

UNWIND case when size(rels(path)) = 0 then [null] else rels(path) end  as rel
InverseFalcon
  • 29,576
  • 4
  • 38
  • 51
  • Thanks, working perfectly :). Can you please share its documentation/blog when i can learn in detail about UNWIND. – Awais Khan Nov 22 '17 at 08:14
  • Here's the [documentation for UNWIND](https://neo4j.com/docs/developer-manual/current/cypher/clauses/unwind/). While it's true that it expands lists into rows, it's not quite made clear this is a multiplicative operation, and that an empty list means the associated row will be wiped out. – InverseFalcon Nov 22 '17 at 08:27