cancel
Showing results for 
Search instead for 
Did you mean: 

Head's Up! These forums are read-only. All users and content have migrated. Please join us at community.neo4j.com.

Getting all connected nodes in a dict

munshine
Node Clone

Hello,

I'm trying to make a query that would give me all the nodes of a certain label, associated with all of the nodes connected to them (node label, node property, relationship type).

For now I got this

MATCH (n:User)
MATCH (n)-[r]-(o)
RETURN n as node, collect(o), collect(labels(o)), collect(TYPE(r))

But this is not ideal, as I would have to to the mapping later, relying on the fact that the lists in column 2, 3, 4 are in the same order.

What I'd like to get would be this result:

Node Neighbors
{name: 'John', last_name: 'Doe' } [{label: 'Dog', type:'HAS_DOG', properties: {name: 'Charlie', good_boy: true}]

How could I achieve this ?

1 ACCEPTED SOLUTION

MATCH (n:User)
OPTIONAL MATCH (n)-[r]-(o)
WITH n as Node,{label:labels(o),type:type(r),properties: o} as Neighbor
WITH Node, collect(Neighbour) as Neighbor s
RETURN Node, Neighbors

This will show all the Neighbors in one row

View solution in original post

6 REPLIES 6

rushikesh
Node Clone

Hey @munshine, you can create a map to get the desired output. Like,

MATCH (n:User)-[r]-(o)
WITH n as Node,{label:labels(o),type:type(r),properties: o} as Neighbors
RETURN Node, Neighbors

Perfect, now I think I understand more how to use WITH clause. Although I'm wondering something: I also need to return User nodes that have no relationships. That would happen with that statement, right ?

No, for that you have to break the MATCH pattern into two, like
MATCH (u:User)
OPTIONAL MATCH (u)-[rel]->(o)

Thanks, but actually after testing I'm noticing I was not very clear, because with your first answer, if a user has several relationship, it returns one row per relationship, when what I'm trying to get in one row per user, with all its immediate connected nodes. Does that make sense ?

MATCH (n:User)
OPTIONAL MATCH (n)-[r]-(o)
WITH n as Node,{label:labels(o),type:type(r),properties: o} as Neighbor
WITH Node, collect(Neighbour) as Neighbor s
RETURN Node, Neighbors

This will show all the Neighbors in one row

munshine
Node Clone

Thanks a lot, this is exactly it. I'm finding hard to understand how this double WITH clause works, but this is mindblowing!