cancel
Showing results for 
Search instead for 
Did you mean: 

How to get all the nodes with and without relationships

manjeetthakur
Node Clone

I am just trying to learn Neo4j with cyper 

here is the use case I want to find all the nodes with and without relationships 

 

 
match p=(a)-[]->(b)
with p limit 25
unwind nodes(p) as n unwind relationships(p) as r
with collect( distinct {id: ID(n), label: COALESCE(n.name, n.title)}) as nl,
collect( distinct {id: ID(r), source: ID(startnode(r)), target: ID(endnode(r)), label: TYPE(r)}) as rl
RETURN {nodes: nl, relationships: rl}
 
but this query only returns nodes that have relationships but I also want to return all nodes that don't have relationships and want to merge the list with nl

Thank you so much 
 
1 REPLY 1

glilienfield
Ninja
Ninja

Try the following if you want a list of each node that includes its list of relationships. Nodes without relationships will have null values for the relationship properties:

 

match(n)
optional match (n)-[r]-()
with id(n) as node, collect({id: id(r), type: type(r), startNode: id(startNode(r)), endNode: id(endNode(r))}) as rel
return {node: node, relationships: rel}

 

 Try the following if you just want a list of all nodes and all relationships not correlated with each other:

 

match(n)
with collect({id: id(n), labels: labels(n)}) as nodes
call {
    match (x)-[r]-(y)
    where id(x) < id(y)
    return collect({id:r, type: type(r), startNode: id(startNode(r)), endNode: id(endNode(r))}) as relationships
}
return nodes, relationships

 

Change the node's 'label' property to be what you want, and/or add additional properties from the node.