2
votes

I have a node that has relevant data that I need. That node has a relationship with multiple nodes. I would like to return the node, and the count of relationships as part of the source data. Ex:

(:Person)-[:Traveled]->(:Country)

(John)-[:Traveled]->(USA)
                  ->(Japan)
                  ->(Spain)

Plain English: John traveled to USA, Japan and Spain

I would like to return Person such that the node includes the number of countries traveled to:

{name:'John',..., numberOfCountriesTraveledTo: 3}

How can I append the result of count(:Country) as a field in John?

UPDATE

What if I had a relationship between two people (say friends) and I needed the path between them including the Person nodes such that the Person nodes included the count(Country)? Such that:

(:Person)-[:Traveled]->(:Country)

(John)-[:Traveled]->(USA)
                  ->(Japan)
                  ->(Spain)

(Kate)-[:Traveled]->(Chile)
                  ->(France)

f=(Kate)-[:Friends]-(John)

And returning f yields a a path with a start node something like

{name:'Kate',..., numberOfCountriesTraveledTo: 2}

and end node like

{name:'John',..., numberOfCountriesTraveledTo: 3}

My goal is to be able to return a path that includes their relationship with the count of countries in the nodes.

1

1 Answers

3
votes

You could just add numberOfCountriesTraveledTo as an additional attribute in the user projection of the result.

MATCH (user:User {name: 'John'})-[:TRAVELED]->(country:Country)
RETURN user{.*, numberOfCountriesTraveledTo: count(country)}

UPDATE - added second answer per Op's request

MATCH (user:User {name: 'John'})<-[:FRIENDS]-(user2:User {name: 'Kate'})
RETURN user{.*, numberOfCountriesTraveledTo: size((user)-[:TRAVELED]->())},
       user2{.*, numberOfCountriesTraveledTo: size((user2)-[:TRAVELED]->())}

For n friends in a path...

MATCH path=(:User {name: 'John'})<-[:FRIENDS*..10]-(:User {name: 'Kate'})
UNWIND nodes(path) as user
WITH user{.*, numberOfCountriesTraveledTo: size((user)-[:TRAVELED]->())} as user
RETURN collect(user) as users